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