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/Messages.h"
29 #include "support/os.h"
30 #include "support/Package.h"
40 using namespace lyx::support;
41 using namespace lyx::support::os;
47 void warning(docstring const & title, docstring const & message,
57 // Dummy translation support
59 Messages const & getMessages(std::string const &)
65 Messages const & getGuiMessages()
71 // Keep the linker happy on Windows
76 string const trim(string const & a, char const * p)
83 size_t r = a.find_last_not_of(p);
84 size_t l = a.find_first_not_of(p);
86 // Is this the minimal test? (lgb)
87 if (r == string::npos && l == string::npos)
90 return a.substr(l, r - l + 1);
94 void split(string const & s, vector<string> & result, char delim)
96 //cerr << "split 1: '" << s << "'\n";
99 while (getline(is, t, delim))
101 //cerr << "split 2\n";
105 string join(vector<string> const & input, char const * delim)
108 for (size_t i = 0; i != input.size(); ++i) {
117 char const * const * is_known(string const & str, char const * const * what)
119 for ( ; *what; ++what)
127 // current stack of nested environments
128 vector<string> active_environments;
131 string active_environment()
133 return active_environments.empty() ? string() : active_environments.back();
137 CommandMap known_commands;
138 CommandMap known_environments;
139 CommandMap known_math_environments;
142 void add_known_command(string const & command, string const & o1,
145 // We have to handle the following cases:
146 // definition o1 o2 invocation result
147 // \newcommand{\foo}{bar} "" false \foo bar
148 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
149 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
150 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
151 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
152 unsigned int nargs = 0;
153 vector<ArgumentType> arguments;
154 string const opt1 = rtrim(ltrim(o1, "["), "]");
155 if (isStrUnsignedInt(opt1)) {
156 // The command has arguments
157 nargs = convert<unsigned int>(opt1);
158 if (nargs > 0 && o2) {
159 // The first argument is optional
160 arguments.push_back(optional);
164 for (unsigned int i = 0; i < nargs; ++i)
165 arguments.push_back(required);
166 known_commands[command] = arguments;
170 bool noweb_mode = false;
177 * Read one command definition from the syntax file
179 void read_command(Parser & p, string command, CommandMap & commands)
181 if (p.next_token().asInput() == "*") {
185 vector<ArgumentType> arguments;
186 while (p.next_token().cat() == catBegin ||
187 p.next_token().asInput() == "[") {
188 if (p.next_token().cat() == catBegin) {
189 string const arg = p.getArg('{', '}');
190 if (arg == "translate")
191 arguments.push_back(required);
192 else if (arg == "item")
193 arguments.push_back(item);
195 arguments.push_back(verbatim);
198 arguments.push_back(optional);
201 commands[command] = arguments;
206 * Read a class of environments from the syntax file
208 void read_environment(Parser & p, string const & begin,
209 CommandMap & environments)
213 Token const & t = p.get_token();
214 if (t.cat() == catLetter)
215 environment += t.asInput();
216 else if (!environment.empty()) {
218 read_command(p, environment, environments);
221 if (t.cat() == catEscape && t.asInput() == "\\end") {
222 string const end = p.getArg('{', '}');
231 * Read a list of TeX commands from a reLyX compatible syntax file.
232 * Since this list is used after all commands that have a LyX counterpart
233 * are handled, it does not matter that the "syntax.default" file
234 * has almost all of them listed. For the same reason the reLyX-specific
235 * reLyXre environment is ignored.
237 void read_syntaxfile(FileName const & file_name)
239 ifdocstream is(file_name.toFilesystemEncoding().c_str());
241 cerr << "Could not open syntax file \"" << file_name
242 << "\" for reading." << endl;
245 // We can use our TeX parser, since the syntax of the layout file is
246 // modeled after TeX.
247 // Unknown tokens are just silently ignored, this helps us to skip some
248 // reLyX specific things.
251 Token const & t = p.get_token();
252 if (t.cat() == catEscape) {
253 string const command = t.asInput();
254 if (command == "\\begin") {
255 string const name = p.getArg('{', '}');
256 if (name == "environments" || name == "reLyXre")
257 // We understand "reLyXre", but it is
258 // not as powerful as "environments".
259 read_environment(p, name,
261 else if (name == "mathenvironments")
262 read_environment(p, name,
263 known_math_environments);
265 read_command(p, command, known_commands);
272 string documentclass;
273 string default_encoding;
275 bool overwrite_files = false;
278 /// return the number of arguments consumed
279 typedef int (*cmd_helper)(string const &, string const &);
282 int parse_help(string const &, string const &)
284 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
286 "\t-c textclass Declare the textclass.\n"
287 "\t-e encoding Set the default encoding (latex name).\n"
288 "\t-f Force overwrite of .lyx files.\n"
289 "\t-help Print this message and quit.\n"
290 "\t-n translate a noweb (aka literate programming) file.\n"
291 "\t-s syntaxfile read additional syntax file.\n"
292 "\t-sysdir dir Set system directory to DIR.\n"
293 "\t-userdir DIR Set user directory to DIR."
299 void error_message(string const & message)
301 cerr << "tex2lyx: " << message << "\n\n";
303 parse_help(string(), string());
307 int parse_class(string const & arg, string const &)
310 error_message("Missing textclass string after -c switch");
316 int parse_encoding(string const & arg, string const &)
319 error_message("Missing encoding string after -e switch");
320 default_encoding = arg;
325 int parse_syntaxfile(string const & arg, string const &)
328 error_message("Missing syntaxfile string after -s switch");
329 syntaxfile = internal_path(arg);
334 // Filled with the command line arguments "foo" of "-sysdir foo" or
336 string cl_system_support;
337 string cl_user_support;
340 int parse_sysdir(string const & arg, string const &)
343 error_message("Missing directory for -sysdir switch");
344 cl_system_support = internal_path(arg);
349 int parse_userdir(string const & arg, string const &)
352 error_message("Missing directory for -userdir switch");
353 cl_user_support = internal_path(arg);
358 int parse_force(string const &, string const &)
360 overwrite_files = true;
365 int parse_noweb(string const &, string const &)
372 void easyParse(int & argc, char * argv[])
374 map<string, cmd_helper> cmdmap;
376 cmdmap["-c"] = parse_class;
377 cmdmap["-e"] = parse_encoding;
378 cmdmap["-f"] = parse_force;
379 cmdmap["-s"] = parse_syntaxfile;
380 cmdmap["-help"] = parse_help;
381 cmdmap["--help"] = parse_help;
382 cmdmap["-n"] = parse_noweb;
383 cmdmap["-sysdir"] = parse_sysdir;
384 cmdmap["-userdir"] = parse_userdir;
386 for (int i = 1; i < argc; ++i) {
387 map<string, cmd_helper>::const_iterator it
388 = cmdmap.find(argv[i]);
390 // don't complain if not found - may be parsed later
391 if (it == cmdmap.end()) {
392 if (argv[i][0] == '-')
393 error_message(string("Unknown option `") + argv[i] + "'.");
398 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
399 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
401 int const remove = 1 + it->second(arg, arg2);
403 // Now, remove used arguments by shifting
404 // the following ones remove places down.
405 os::remove_internal_args(i, remove);
407 for (int j = i; j < argc; ++j)
408 argv[j] = argv[j + remove];
414 // path of the first parsed file
415 string masterFilePath;
416 // path of the currently parsed file
417 string parentFilePath;
419 } // anonymous namespace
422 string getMasterFilePath()
424 return masterFilePath;
427 string getParentFilePath()
429 return parentFilePath;
436 * Reads tex input from \a is and writes lyx output to \a os.
437 * Uses some common settings for the preamble, so this should only
438 * be used more than once for included documents.
439 * Caution: Overwrites the existing preamble settings if the new document
440 * contains a preamble.
441 * You must ensure that \p parentFilePath is properly set before calling
444 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
447 if (!encoding.empty())
448 p.setEncoding(encoding);
452 TeX2LyXDocClass textclass;
453 parse_preamble(p, ss, documentclass, textclass);
455 active_environments.push_back("document");
456 Context context(true, textclass);
457 parse_text(p, ss, FLAG_END, true, context);
459 // Empty document body. LyX needs at least one paragraph.
460 context.check_layout(ss);
461 context.check_end_layout(ss);
462 ss << "\n\\end_body\n\\end_document\n";
463 active_environments.pop_back();
468 ofdocstream parsertest("parsertest.tex");
470 parsertest << p.get_token().asInput();
471 // <origfile> and parsertest.tex should now have identical content
476 /// convert TeX from \p infilename to LyX and write it to \p os
477 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
480 // forbid buffering on this stream
481 is.rdbuf()->pubsetbuf(0,0);
482 is.open(infilename.toFilesystemEncoding().c_str());
484 cerr << "Could not open input file \"" << infilename
485 << "\" for reading." << endl;
488 string const oldParentFilePath = parentFilePath;
489 parentFilePath = onlyPath(infilename.absFileName());
490 tex2lyx(is, os, encoding);
491 parentFilePath = oldParentFilePath;
495 } // anonymous namespace
498 bool tex2lyx(string const & infilename, FileName const & outfilename,
499 string const & encoding)
501 if (outfilename.isReadableFile()) {
502 if (overwrite_files) {
503 cerr << "Overwriting existing file "
504 << outfilename << endl;
506 cerr << "Not overwriting existing file "
507 << outfilename << endl;
511 cerr << "Creating file " << outfilename << endl;
513 ofstream os(outfilename.toFilesystemEncoding().c_str());
515 cerr << "Could not open output file \"" << outfilename
516 << "\" for writing." << endl;
520 cerr << "Input file: " << infilename << "\n";
521 cerr << "Output file: " << outfilename << "\n";
523 return tex2lyx(FileName(infilename), os, encoding);
529 int main(int argc, char * argv[])
533 //setlocale(LC_CTYPE, "");
535 lyxerr.setStream(cerr);
537 os::init(argc, argv);
539 easyParse(argc, argv);
542 error_message("Not enough arguments.");
545 init_package(internal_path(os::utf8_argv(0)),
546 cl_system_support, cl_user_support,
547 top_build_dir_is_two_levels_up);
548 } catch (ExceptionMessage const & message) {
549 cerr << to_utf8(message.title_) << ":\n"
550 << to_utf8(message.details_) << endl;
551 if (message.type_ == ErrorException)
555 // Now every known option is parsed. Look for input and output
556 // file name (the latter is optional).
557 string infilename = internal_path(os::utf8_argv(1));
558 infilename = makeAbsPath(infilename).absFileName();
562 outfilename = internal_path(os::utf8_argv(2));
563 if (outfilename != "-")
564 outfilename = makeAbsPath(outfilename).absFileName();
566 outfilename = changeExtension(infilename, ".lyx");
568 // Read the syntax tables
569 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
570 if (system_syntaxfile.empty()) {
571 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
574 read_syntaxfile(system_syntaxfile);
575 if (!syntaxfile.empty())
576 read_syntaxfile(makeAbsPath(syntaxfile));
578 // Read the encodings table.
579 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
580 if (symbols_path.empty()) {
581 cerr << "Error: Could not find file \"unicodesymbols\"."
585 FileName const enc_path = libFileSearch(string(), "encodings");
586 if (enc_path.empty()) {
587 cerr << "Error: Could not find file \"encodings\"."
591 encodings.read(enc_path, symbols_path);
592 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
593 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
595 // The real work now.
596 masterFilePath = onlyPath(infilename);
597 parentFilePath = masterFilePath;
598 if (outfilename == "-") {
599 if (tex2lyx(FileName(infilename), cout, default_encoding))
604 if (tex2lyx(infilename, FileName(outfilename), default_encoding))