]> git.lyx.org Git - lyx.git/blob - src/LayoutFile.cpp
Exporter.cpp: revert r34230 because this interferes with Enrico's new LyXVC feature...
[lyx.git] / src / LayoutFile.cpp
1 /**
2  * \file LayoutFileList.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "LayoutFile.h"
15 #include "Counters.h"
16 #include "Floating.h"
17 #include "FloatList.h"
18 #include "Lexer.h"
19 #include "TextClass.h"
20
21 #include "frontends/alert.h"
22
23 #include "support/debug.h"
24 #include "support/FileName.h"
25 #include "support/filetools.h"
26 #include "support/gettext.h"
27 #include "support/lassert.h"
28 #include "support/lstrings.h"
29
30 #include <boost/bind.hpp>
31 #include <boost/regex.hpp>
32
33 #include <fstream>
34
35 using namespace std;
36 using namespace lyx::support;
37
38 namespace lyx {
39
40 using boost::bind;
41 using boost::regex;
42 using boost::smatch;
43
44 LayoutFile::LayoutFile(string const & fn, string const & cln,
45                            string const & desc, string const & prereq,
46                                  bool texclassavail) 
47 {
48         name_ = fn;
49         latexname_ = cln;
50         description_ = desc;
51         prerequisites_ = prereq;
52         tex_class_avail_ = texclassavail;
53 }
54
55
56 LayoutFileList::~LayoutFileList()
57 {
58         ClassMap::const_iterator it = classmap_.begin();
59         ClassMap::const_iterator en = classmap_.end();
60         for (; it != en; ++it) {
61                 delete it->second;
62         }
63 }
64
65
66 LayoutFileList & LayoutFileList::get() 
67 {
68         static LayoutFileList baseclasslist;
69         return baseclasslist;
70 }
71
72
73 bool LayoutFileList::haveClass(string const & classname) const
74 {
75         ClassMap::const_iterator it = classmap_.begin();
76         ClassMap::const_iterator en = classmap_.end();
77         for (; it != en; ++it) {
78                 if (it->first == classname)
79                         return true;
80         }
81         return false;
82 }
83
84
85 LayoutFile const & LayoutFileList::operator[](string const & classname) const
86 {
87         LASSERT(haveClass(classname), /**/);
88         return *classmap_[classname];
89 }
90
91
92 LayoutFile & LayoutFileList::operator[](string const & classname)
93 {
94         LASSERT(haveClass(classname), /**/);
95         return *classmap_[classname];
96 }
97
98
99 // Reads LyX textclass definitions according to textclass config file
100 bool LayoutFileList::read()
101 {
102         bool success = false;
103         Lexer lex;
104         FileName const real_file = libFileSearch("", "textclass.lst");
105         LYXERR(Debug::TCLASS, "Reading textclasses from `" << real_file << "'.");
106
107         if (real_file.empty()) {
108                 LYXERR0("LayoutFileList::Read: unable to find textclass file  `"
109                     << makeDisplayPath(real_file.absFileName(), 1000)
110                     << "'.");
111                 success = false;
112         } else if (!lex.setFile(real_file)) {
113                 LYXERR0("LayoutFileList::Read: lyxlex was not able to set file: "
114                        << real_file << '.');
115         } else if (!lex.isOK()) {
116                 LYXERR0("LayoutFileList::Read: unable to open textclass file  `"
117                        << makeDisplayPath(real_file.absFileName(), 1000)
118                        << "'\nCheck your installation.");
119         } else {
120                 // we have a file we can read.
121                 bool finished = false;
122                 LYXERR(Debug::TCLASS, "Starting parsing of textclass.lst");
123                 while (lex.isOK() && !finished) {
124                         LYXERR(Debug::TCLASS, "\tline by line");
125                         switch (lex.lex()) {
126                         case Lexer::LEX_FEOF:
127                                 finished = true;
128                                 break;
129                         default:
130                                 string const fname = lex.getString();
131                                 LYXERR(Debug::TCLASS, "Fname: " << fname);
132                                 if (!lex.next()) 
133                                         break;
134                                 string const clname = lex.getString();
135                                 LYXERR(Debug::TCLASS, "Clname: " << clname);
136                                 if (!lex.next()) 
137                                         break;
138                                 string const desc = lex.getString();
139                                 LYXERR(Debug::TCLASS, "Desc: " << desc);
140                                 if (!lex.next()) 
141                                         break;
142                                 bool avail = lex.getBool();
143                                 LYXERR(Debug::TCLASS, "Avail: " << avail);
144                                 if (!lex.next()) 
145                                         break;
146                                 string const prereq = lex.getString();
147                                 LYXERR(Debug::TCLASS, "Prereq: " << prereq);
148                                 // This code is run when we have
149                                 // fname, clname, desc, prereq, and avail
150                                 LayoutFile * tmpl = new LayoutFile(fname, clname, desc, prereq, avail);
151                                 if (lyxerr.debugging(Debug::TCLASS)) {
152                                         // only system layout files are loaded here so no
153                                         // buffer path is needed.
154                                         tmpl->load();
155                                 }
156                                 classmap_[fname] = tmpl;
157                         } // end of switch
158                 } // end of while loop
159                 LYXERR(Debug::TCLASS, "End parsing of textclass.lst");
160                 success = true;
161         } // end of else
162
163         // LyX will start with an empty classmap_. This is OK because
164         // (a) we will give the user a chance to reconfigure (see bug 2829) and
165         // (b) even if that fails, we can use addEmptyClass() to get some basic
166         // functionality.
167         if (classmap_.empty())
168                 LYXERR0("LayoutFileList::Read: no textclasses found!");
169         return success;
170 }
171
172
173 std::vector<LayoutFileIndex> LayoutFileList::classList() const
174 {
175         std::vector<LayoutFileIndex> cl;
176         ClassMap::const_iterator it = classmap_.begin();
177         ClassMap::const_iterator en = classmap_.end();
178         for (; it != en; ++it)
179                 cl.push_back(it->first);
180         return cl;
181 }
182
183
184 void LayoutFileList::reset(LayoutFileIndex const & classname) {
185         LASSERT(haveClass(classname), /**/);
186         LayoutFile * tc = classmap_[classname];
187         LayoutFile * tmpl = 
188                 new LayoutFile(tc->name(), tc->latexname(), tc->description(),
189                                tc->prerequisites(), tc->isTeXClassAvailable());
190         classmap_[classname] = tmpl;
191         delete tc;
192 }
193
194
195 namespace {
196
197 string layoutpost =                     
198                 "Columns      1\n"
199                 "Sides        1\n"
200                 "SecNumDepth  2\n"
201                 "TocDepth     2\n"
202                 "DefaultStyle   Standard\n\n"
203                 "Style Standard\n"
204                 "       Category              MainText\n"
205                 "       Margin                Static\n"
206                 "       LatexType             Paragraph\n"
207                 "       LatexName             dummy\n"
208                 "       ParIndent             MM\n"
209                 "       ParSkip               0.4\n"
210                 "       Align                 Block\n"
211                 "       AlignPossible         Block, Left, Right, Center\n"
212                 "       LabelType             No_Label\n"
213                 "End\n";
214         
215 }
216
217 LayoutFileIndex LayoutFileList::addEmptyClass(string const & textclass)
218 {
219         FileName const tempLayout = FileName::tempName();
220         ofstream ofs(tempLayout.toFilesystemEncoding().c_str());
221         // This writes a very basic class, but it also attempts to include 
222         // stdclass.inc. That would give us something moderately usable.
223         ofs << "# This layout is automatically generated\n"
224                "# \\DeclareLaTeXClass{" << textclass << "}\n\n"
225                "Format 26\n"
226                "Input stdclass.inc\n\n"
227             << layoutpost;
228         ofs.close();
229
230         // We do not know if a LaTeX class is available for this document, but setting
231         // the last parameter to true will suppress a warning message about missing
232         // tex class.
233         LayoutFile * tc = new LayoutFile(textclass, textclass, 
234                         "Unknown text class " + textclass, textclass + ".cls", true);
235
236         if (!tc->load(tempLayout.absFileName())) {
237                 // The only way this happens is because the hardcoded layout file 
238                 // aboveis wrong or stdclass.inc cannot be found. So try again 
239                 // without stdclass.inc.
240                 ofstream ofs2(tempLayout.toFilesystemEncoding().c_str());
241                 ofs2 << "# This layout is automatically generated\n"
242                         "# \\DeclareLaTeXClass{" << textclass << "}\n\n"
243                         "Format 26\n"
244                         "Input stdclass.inc\n\n"
245                      << layoutpost;
246                 ofs2.close();
247                 if (!tc->load(tempLayout.absFileName())) {
248                         // This can only happen if the hardcoded file above is wrong.
249                         LASSERT(false, /* */);
250                 }
251         }
252
253         classmap_[textclass] = tc;
254         return textclass;
255 }
256
257
258 LayoutFileIndex 
259         LayoutFileList::addLocalLayout(string const & textclass, string const & path)
260 {
261         // FIXME  There is a bug here: 4593
262         //
263         // only check for textclass.layout file, .cls can be anywhere in $TEXINPUTS
264         // NOTE: latex class name is defined in textclass.layout, which can be 
265         // different from textclass
266         string fullName = addName(path, textclass + ".layout");
267         
268         FileName const layout_file(fullName);
269         if (layout_file.exists()) {
270                 LYXERR(Debug::TCLASS, "Adding class " << textclass << " from directory " << path);
271                 // Read .layout file and get description, real latex classname etc
272                 //
273                 // This is a C++ version of function processLayoutFile in configure.py,
274                 // which uses the following regex
275                 //     \Declare(LaTeX|DocBook)Class\s*(\[([^,]*)(,.*)*\])*\s*{(.*)}
276                 ifstream ifs(layout_file.toFilesystemEncoding().c_str());
277                 static regex const reg("^#\\s*\\\\Declare(LaTeX|DocBook)Class\\s*"
278                         "(?:\\[([^,]*)(?:,.*)*\\])*\\s*\\{(.*)\\}\\s*");
279                 string line;
280                 while (getline(ifs, line)) {
281                         // look for the \DeclareXXXClass line
282                         smatch sub;
283                         if (regex_match(line, sub, reg)) {
284                                 // returns: whole string, classtype (not used here), class name, description
285                                 LASSERT(sub.size() == 4, /**/);
286                                 // now, create a TextClass with description containing path information
287                                 string class_name(sub.str(2) == "" ? textclass : sub.str(2));
288                                 string class_prereq(class_name + ".cls");
289                                 LayoutFile * tmpl = 
290                                         new LayoutFile(textclass, class_name, textclass, class_prereq, true);
291                                 //FIXME: The prerequisites are available from the layout file and
292                                 //       can be extracted from the above regex, but for now this
293                                 //       field is simply set to class_name + ".cls"
294                                 // This textclass is added on request so it will definitely be
295                                 // used. Load it now because other load() calls may fail if they
296                                 // are called in a context without buffer path information.
297                                 tmpl->load(path);
298                                 // There will be only one textclass with this name, even if different
299                                 // layout files are loaded from different directories.
300                                 if (haveClass(textclass)) {
301                                         LYXERR0("Existing textclass " << textclass << " is redefined by " << fullName);
302                                         delete classmap_[textclass];
303                                 }
304                                 classmap_[textclass] = tmpl;
305                                 return textclass;
306                         }
307                 }
308         }
309         // If .layout is not in local directory, or an invalid layout is found, return null
310         return string();
311 }
312
313
314 bool LayoutFileList::load(string const & name, string const & buf_path)
315 {
316         if (!haveClass(name)) {
317                 LYXERR0("Document class \"" << name << "\" does not exist.");
318                 return false;
319         }
320
321         LayoutFile * tc = classmap_[name];
322         if (!tc->load(buf_path)) {
323                 docstring s = bformat(_("The document class %1$s "
324                                    "could not be loaded."), from_utf8(name));
325                 frontend::Alert::error(_("Could not load class"), s);
326                 return false;
327         }
328         return true;
329 }
330
331
332 LayoutFileIndex defaultBaseclass()
333 {
334         if (LayoutFileList::get().haveClass("article"))
335                 return string("article");
336         if (LayoutFileList::get().empty())
337                 // we'll call it that, since this gives the user a chance to
338                 // have a functioning document when things improve.
339                 return string("article");
340         return LayoutFileList::get().classList().front();
341 }
342
343 } // namespace lyx