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