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