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.
20 #include "TextClass.h"
22 #include "support/convert.h"
23 #include "support/debug.h"
24 #include "support/ExceptionMessage.h"
25 #include "support/filetools.h"
26 #include "support/lassert.h"
27 #include "support/lstrings.h"
28 #include "support/os.h"
29 #include "support/Package.h"
39 using namespace lyx::support;
40 using namespace lyx::support::os;
44 string const trim(string const & a, char const * p)
51 size_t r = a.find_last_not_of(p);
52 size_t l = a.find_first_not_of(p);
54 // Is this the minimal test? (lgb)
55 if (r == string::npos && l == string::npos)
58 return a.substr(l, r - l + 1);
62 void split(string const & s, vector<string> & result, char delim)
64 //cerr << "split 1: '" << s << "'\n";
67 while (getline(is, t, delim))
69 //cerr << "split 2\n";
73 string join(vector<string> const & input, char const * delim)
76 for (size_t i = 0; i != input.size(); ++i) {
85 char const * const * is_known(string const & str, char const * const * what)
87 for ( ; *what; ++what)
95 // current stack of nested environments
96 vector<string> active_environments;
99 string active_environment()
101 return active_environments.empty() ? string() : active_environments.back();
105 CommandMap known_commands;
106 CommandMap known_environments;
107 CommandMap known_math_environments;
110 void add_known_command(string const & command, string const & o1,
113 // We have to handle the following cases:
114 // definition o1 o2 invocation result
115 // \newcommand{\foo}{bar} "" false \foo bar
116 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
117 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
118 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
119 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
120 unsigned int nargs = 0;
121 vector<ArgumentType> arguments;
122 string const opt1 = rtrim(ltrim(o1, "["), "]");
123 if (isStrUnsignedInt(opt1)) {
124 // The command has arguments
125 nargs = convert<unsigned int>(opt1);
126 if (nargs > 0 && o2) {
127 // The first argument is optional
128 arguments.push_back(optional);
132 for (unsigned int i = 0; i < nargs; ++i)
133 arguments.push_back(required);
134 known_commands[command] = arguments;
138 bool noweb_mode = false;
145 * Read one command definition from the syntax file
147 void read_command(Parser & p, string command, CommandMap & commands)
149 if (p.next_token().asInput() == "*") {
153 vector<ArgumentType> arguments;
154 while (p.next_token().cat() == catBegin ||
155 p.next_token().asInput() == "[") {
156 if (p.next_token().cat() == catBegin) {
157 string const arg = p.getArg('{', '}');
158 if (arg == "translate")
159 arguments.push_back(required);
161 arguments.push_back(verbatim);
164 arguments.push_back(optional);
167 commands[command] = arguments;
172 * Read a class of environments from the syntax file
174 void read_environment(Parser & p, string const & begin,
175 CommandMap & environments)
179 Token const & t = p.get_token();
180 if (t.cat() == catLetter)
181 environment += t.asInput();
182 else if (!environment.empty()) {
184 read_command(p, environment, environments);
187 if (t.cat() == catEscape && t.asInput() == "\\end") {
188 string const end = p.getArg('{', '}');
197 * Read a list of TeX commands from a reLyX compatible syntax file.
198 * Since this list is used after all commands that have a LyX counterpart
199 * are handled, it does not matter that the "syntax.default" file
200 * has almost all of them listed. For the same reason the reLyX-specific
201 * reLyXre environment is ignored.
203 void read_syntaxfile(FileName const & file_name)
205 ifdocstream is(file_name.toFilesystemEncoding().c_str());
207 cerr << "Could not open syntax file \"" << file_name
208 << "\" for reading." << endl;
211 // We can use our TeX parser, since the syntax of the layout file is
212 // modeled after TeX.
213 // Unknown tokens are just silently ignored, this helps us to skip some
214 // reLyX specific things.
217 Token const & t = p.get_token();
218 if (t.cat() == catEscape) {
219 string const command = t.asInput();
220 if (command == "\\begin") {
221 string const name = p.getArg('{', '}');
222 if (name == "environments" || name == "reLyXre")
223 // We understand "reLyXre", but it is
224 // not as powerful as "environments".
225 read_environment(p, name,
227 else if (name == "mathenvironments")
228 read_environment(p, name,
229 known_math_environments);
231 read_command(p, command, known_commands);
238 string documentclass;
239 string default_encoding;
241 bool overwrite_files = false;
244 /// return the number of arguments consumed
245 typedef int (*cmd_helper)(string const &, string const &);
248 int parse_help(string const &, string const &)
250 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
251 "Command line switches (case sensitive):\n"
252 "\t-help summarize tex2lyx usage\n"
253 "\t-f Force creation of .lyx files even if they exist already\n"
254 "\t-userdir dir try to set user directory to dir\n"
255 "\t-sysdir dir try to set system directory to dir\n"
256 "\t-c textclass declare the textclass\n"
257 "\t-e encoding set the default encoding (latex name)\n"
258 "\t-n translate a noweb (aka literate programming) file.\n"
259 "\t-s syntaxfile read additional syntax file" << endl;
264 int parse_class(string const & arg, string const &)
267 cerr << "Missing textclass string after -c switch" << endl;
275 int parse_encoding(string const & arg, string const &)
278 cerr << "Missing encoding string after -e switch" << endl;
281 default_encoding = arg;
286 int parse_syntaxfile(string const & arg, string const &)
289 cerr << "Missing syntaxfile string after -s switch" << endl;
292 syntaxfile = internal_path(arg);
297 // Filled with the command line arguments "foo" of "-sysdir foo" or
299 string cl_system_support;
300 string cl_user_support;
303 int parse_sysdir(string const & arg, string const &)
306 cerr << "Missing directory for -sysdir switch" << endl;
309 cl_system_support = internal_path(arg);
314 int parse_userdir(string const & arg, string const &)
317 cerr << "Missing directory for -userdir switch" << endl;
320 cl_user_support = internal_path(arg);
325 int parse_force(string const &, string const &)
327 overwrite_files = true;
332 int parse_noweb(string const &, string const &)
339 void easyParse(int & argc, char * argv[])
341 map<string, cmd_helper> cmdmap;
343 cmdmap["-c"] = parse_class;
344 cmdmap["-e"] = parse_encoding;
345 cmdmap["-f"] = parse_force;
346 cmdmap["-s"] = parse_syntaxfile;
347 cmdmap["-help"] = parse_help;
348 cmdmap["--help"] = parse_help;
349 cmdmap["-n"] = parse_noweb;
350 cmdmap["-sysdir"] = parse_sysdir;
351 cmdmap["-userdir"] = parse_userdir;
353 for (int i = 1; i < argc; ++i) {
354 map<string, cmd_helper>::const_iterator it
355 = cmdmap.find(argv[i]);
357 // don't complain if not found - may be parsed later
358 if (it == cmdmap.end())
361 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
362 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
364 int const remove = 1 + it->second(arg, arg2);
366 // Now, remove used arguments by shifting
367 // the following ones remove places down.
369 for (int j = i; j < argc; ++j)
370 argv[j] = argv[j + remove];
376 // path of the first parsed file
377 string masterFilePath;
378 // path of the currently parsed file
379 string parentFilePath;
381 } // anonymous namespace
384 string getMasterFilePath()
386 return masterFilePath;
389 string getParentFilePath()
391 return parentFilePath;
398 * Reads tex input from \a is and writes lyx output to \a os.
399 * Uses some common settings for the preamble, so this should only
400 * be used more than once for included documents.
401 * Caution: Overwrites the existing preamble settings if the new document
402 * contains a preamble.
403 * You must ensure that \p parentFilePath is properly set before calling
406 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
409 if (!encoding.empty())
410 p.setEncoding(encoding);
414 TeX2LyXDocClass textclass;
415 parse_preamble(p, ss, documentclass, textclass);
417 active_environments.push_back("document");
418 Context context(true, textclass);
419 parse_text(p, ss, FLAG_END, true, context);
421 // Empty document body. LyX needs at least one paragraph.
422 context.check_layout(ss);
423 context.check_end_layout(ss);
424 ss << "\n\\end_body\n\\end_document\n";
425 active_environments.pop_back();
430 ofdocstream parsertest("parsertest.tex");
432 parsertest << p.get_token().asInput();
433 // <origfile> and parsertest.tex should now have identical content
438 /// convert TeX from \p infilename to LyX and write it to \p os
439 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
442 // forbid buffering on this stream
443 is.rdbuf()->pubsetbuf(0,0);
444 is.open(infilename.toFilesystemEncoding().c_str());
446 cerr << "Could not open input file \"" << infilename
447 << "\" for reading." << endl;
450 string const oldParentFilePath = parentFilePath;
451 parentFilePath = onlyPath(infilename.absFilename());
452 tex2lyx(is, os, encoding);
453 parentFilePath = oldParentFilePath;
457 } // anonymous namespace
460 bool tex2lyx(string const & infilename, FileName const & outfilename,
461 string const & encoding)
463 if (outfilename.isReadableFile()) {
464 if (overwrite_files) {
465 cerr << "Overwriting existing file "
466 << outfilename << endl;
468 cerr << "Not overwriting existing file "
469 << outfilename << endl;
473 cerr << "Creating file " << outfilename << endl;
475 ofstream os(outfilename.toFilesystemEncoding().c_str());
477 cerr << "Could not open output file \"" << outfilename
478 << "\" for writing." << endl;
482 cerr << "Input file: " << infilename << "\n";
483 cerr << "Output file: " << outfilename << "\n";
485 return tex2lyx(FileName(infilename), os, encoding);
491 int main(int argc, char * argv[])
495 //setlocale(LC_CTYPE, "");
497 lyxerr.setStream(cerr);
499 easyParse(argc, argv);
502 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
503 "See tex2lyx -help." << endl;
507 os::init(argc, argv);
510 init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
511 cl_system_support, cl_user_support,
512 top_build_dir_is_two_levels_up);
513 } catch (ExceptionMessage const & message) {
514 cerr << to_utf8(message.title_) << ":\n"
515 << to_utf8(message.details_) << endl;
516 if (message.type_ == ErrorException)
520 // Now every known option is parsed. Look for input and output
521 // file name (the latter is optional).
522 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
523 infilename = makeAbsPath(infilename).absFilename();
527 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
528 if (outfilename != "-")
529 outfilename = makeAbsPath(outfilename).absFilename();
531 outfilename = changeExtension(infilename, ".lyx");
533 // Read the syntax tables
534 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
535 if (system_syntaxfile.empty()) {
536 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
539 read_syntaxfile(system_syntaxfile);
540 if (!syntaxfile.empty())
541 read_syntaxfile(makeAbsPath(syntaxfile));
543 // Read the encodings table.
544 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
545 if (symbols_path.empty()) {
546 cerr << "Error: Could not find file \"unicodesymbols\"."
550 FileName const enc_path = libFileSearch(string(), "encodings");
551 if (enc_path.empty()) {
552 cerr << "Error: Could not find file \"encodings\"."
556 encodings.read(enc_path, symbols_path);
558 // The real work now.
559 masterFilePath = onlyPath(infilename);
560 parentFilePath = masterFilePath;
561 if (outfilename == "-") {
562 if (tex2lyx(FileName(infilename), cout, default_encoding))
567 if (tex2lyx(infilename, FileName(outfilename), default_encoding))