]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
Replace the PainterInfo::erased_ member by a proper Change object and remove the...
[lyx.git] / src / TextClass.cpp
1 /**
2  * \file TextClass.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 Jean-Marc Lasgouttes
8  * \author Angus Leeming
9  * \author John Levon
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "TextClass.h"
18
19 #include "LayoutFile.h"
20 #include "Color.h"
21 #include "Counters.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "Layout.h"
25 #include "Lexer.h"
26 #include "Font.h"
27
28 #include "frontends/alert.h"
29
30 #include "support/lassert.h"
31 #include "support/debug.h"
32 #include "support/ExceptionMessage.h"
33 #include "support/FileName.h"
34 #include "support/filetools.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37 #include "support/os.h"
38
39 #include <algorithm>
40 #include <fstream>
41 #include <sstream>
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47
48 namespace {
49
50 class LayoutNamesEqual : public unary_function<Layout, bool> {
51 public:
52         LayoutNamesEqual(docstring const & name)
53                 : name_(name)
54         {}
55         bool operator()(Layout const & c) const
56         {
57                 return c.name() == name_;
58         }
59 private:
60         docstring name_;
61 };
62
63 // Keep the changes documented in the Customization manual. 
64 int const FORMAT = 13;
65
66
67 bool layout2layout(FileName const & filename, FileName const & tempfile)
68 {
69         FileName const script = libFileSearch("scripts", "layout2layout.py");
70         if (script.empty()) {
71                 LYXERR0("Could not find layout conversion "
72                           "script layout2layout.py.");
73                 return false;
74         }
75
76         ostringstream command;
77         command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
78                 << ' ' << quoteName(filename.toFilesystemEncoding())
79                 << ' ' << quoteName(tempfile.toFilesystemEncoding());
80         string const command_str = command.str();
81
82         LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
83
84         cmd_ret const ret = runCommand(command_str);
85         if (ret.first != 0) {
86                 LYXERR0("Could not run layout conversion script layout2layout.py.");
87                 return false;
88         }
89         return true;
90 }
91
92
93 std::string translateRT(TextClass::ReadType rt) 
94 {
95         switch (rt) {
96         case TextClass::BASECLASS:
97                 return "textclass";
98         case TextClass::MERGE:
99                 return "input file";
100         case TextClass::MODULE:
101                 return "module file";
102         case TextClass::VALIDATION:
103                 return "validation";
104         }
105         // shutup warning
106         return string();
107 }
108
109 } // namespace anon
110
111
112 // This string should not be translated here, 
113 // because it is a layout identifier.
114 docstring const TextClass::plain_layout_ = from_ascii("Plain Layout");
115
116
117 InsetLayout DocumentClass::plain_insetlayout_;
118
119
120 /////////////////////////////////////////////////////////////////////////
121 //
122 // TextClass
123 //
124 /////////////////////////////////////////////////////////////////////////
125
126 TextClass::TextClass()
127 {
128         outputType_ = LATEX;
129         columns_ = 1;
130         sides_ = OneSide;
131         secnumdepth_ = 3;
132         tocdepth_ = 3;
133         pagestyle_ = "default";
134         defaultfont_ = sane_font;
135         opt_fontsize_ = "10|11|12";
136         opt_pagestyle_ = "empty|plain|headings|fancy";
137         titletype_ = TITLE_COMMAND_AFTER;
138         titlename_ = "maketitle";
139         loaded_ = false;
140         _("Plain Layout"); // a hack to make this translatable
141 }
142
143
144 bool TextClass::readStyle(Lexer & lexrc, Layout & lay) const
145 {
146         LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
147         if (!lay.read(lexrc, *this)) {
148                 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
149                 return false;
150         }
151         // Resolve fonts
152         lay.resfont = lay.font;
153         lay.resfont.realize(defaultfont_);
154         lay.reslabelfont = lay.labelfont;
155         lay.reslabelfont.realize(defaultfont_);
156         return true; // no errors
157 }
158
159
160 enum TextClassTags {
161         TC_OUTPUTTYPE = 1,
162         TC_INPUT,
163         TC_STYLE,
164         TC_DEFAULTSTYLE,
165         TC_INSETLAYOUT,
166         TC_NOSTYLE,
167         TC_COLUMNS,
168         TC_SIDES,
169         TC_PAGESTYLE,
170         TC_DEFAULTFONT,
171         TC_SECNUMDEPTH,
172         TC_TOCDEPTH,
173         TC_CLASSOPTIONS,
174         TC_PREAMBLE,
175         TC_PROVIDES,
176         TC_REQUIRES,
177         TC_LEFTMARGIN,
178         TC_RIGHTMARGIN,
179         TC_FLOAT,
180         TC_COUNTER,
181         TC_NOFLOAT,
182         TC_TITLELATEXNAME,
183         TC_TITLELATEXTYPE,
184         TC_FORMAT,
185         TC_ADDTOPREAMBLE,
186         TC_DEFAULTMODULE,
187         TC_PROVIDESMODULE,
188         TC_EXCLUDESMODULE
189 };
190
191
192 namespace {
193
194         LexerKeyword textClassTags[] = {
195                 { "addtopreamble",   TC_ADDTOPREAMBLE },
196                 { "classoptions",    TC_CLASSOPTIONS },
197                 { "columns",         TC_COLUMNS },
198                 { "counter",         TC_COUNTER },
199                 { "defaultfont",     TC_DEFAULTFONT },
200                 { "defaultmodule",   TC_DEFAULTMODULE },
201                 { "defaultstyle",    TC_DEFAULTSTYLE },
202                 { "excludesmodule",  TC_EXCLUDESMODULE },
203                 { "float",           TC_FLOAT },
204                 { "format",          TC_FORMAT },
205                 { "input",           TC_INPUT },
206                 { "insetlayout",     TC_INSETLAYOUT },
207                 { "leftmargin",      TC_LEFTMARGIN },
208                 { "nofloat",         TC_NOFLOAT },
209                 { "nostyle",         TC_NOSTYLE },
210                 { "outputtype",      TC_OUTPUTTYPE },
211                 { "pagestyle",       TC_PAGESTYLE },
212                 { "preamble",        TC_PREAMBLE },
213                 { "provides",        TC_PROVIDES },
214                 { "providesmodule",  TC_PROVIDESMODULE },
215                 { "requires",        TC_REQUIRES },
216                 { "rightmargin",     TC_RIGHTMARGIN },
217                 { "secnumdepth",     TC_SECNUMDEPTH },
218                 { "sides",           TC_SIDES },
219                 { "style",           TC_STYLE },
220                 { "titlelatexname",  TC_TITLELATEXNAME },
221                 { "titlelatextype",  TC_TITLELATEXTYPE },
222                 { "tocdepth",        TC_TOCDEPTH }
223         };
224         
225 } //namespace anon
226
227
228 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
229 {
230         LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
231         FileName const tempfile = FileName::tempName("convert_layout");
232         bool success = layout2layout(filename, tempfile);
233         if (success)
234                 success = read(tempfile, rt);
235         tempfile.removeFile();
236         return success;
237 }
238
239 bool TextClass::read(FileName const & filename, ReadType rt)
240 {
241         if (!filename.isReadableFile()) {
242                 lyxerr << "Cannot read layout file `" << filename << "'."
243                        << endl;
244                 return false;
245         }
246
247         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
248                 to_utf8(makeDisplayPath(filename.absFilename())));
249
250         // Define the plain layout used in table cells, ert, etc. Note that 
251         // we do this before loading any layout file, so that classes can 
252         // override features of this layout if they should choose to do so.
253         if (rt == BASECLASS && !hasLayout(plain_layout_))
254                 layoutlist_.push_back(createBasicLayout(plain_layout_));
255
256         Lexer lexrc(textClassTags);
257         lexrc.setFile(filename);
258         ReturnValues retval = read(lexrc, rt);
259         
260         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
261                         to_utf8(makeDisplayPath(filename.absFilename())));
262         
263         if (retval != FORMAT_MISMATCH) 
264                 return retval == OK;
265         
266         bool const worx = convertLayoutFormat(filename, rt);
267         if (!worx) {
268                 LYXERR0 ("Unable to convert " << filename << 
269                         " to format " << FORMAT);
270                 return false;
271         }
272         return true;
273 }
274
275
276 bool TextClass::validate(std::string const & str)
277 {
278         TextClass tc;
279         return tc.read(str, VALIDATION);
280 }
281
282
283 bool TextClass::read(std::string const & str, ReadType rt) 
284 {
285         Lexer lexrc(textClassTags);
286         istringstream is(str);
287         lexrc.setStream(is);
288         ReturnValues retval = read(lexrc, rt);
289
290         if (retval != FORMAT_MISMATCH) 
291                 return retval == OK;
292
293         // write the layout string to a temporary file
294         FileName const tempfile = FileName::tempName("TextClass_read");
295         ofstream os(tempfile.toFilesystemEncoding().c_str());
296         if (!os) {
297                 LYXERR0("Unable to create temporary file");
298                 return false;
299         }
300         os << str;
301         os.close();
302
303         // now try to convert it
304         bool const worx = convertLayoutFormat(tempfile, rt);
305         if (!worx) {
306                 LYXERR0("Unable to convert internal layout information to format " 
307                         << FORMAT);
308         }
309         tempfile.removeFile();
310         return worx;
311 }
312
313
314 // Reads a textclass structure from file.
315 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt) 
316 {
317         bool error = !lexrc.isOK();
318
319         // Format of files before the 'Format' tag was introduced
320         int format = 1;
321
322         // parsing
323         while (lexrc.isOK() && !error) {
324                 int le = lexrc.lex();
325
326                 switch (le) {
327                 case Lexer::LEX_FEOF:
328                         continue;
329
330                 case Lexer::LEX_UNDEF:
331                         lexrc.printError("Unknown TextClass tag `$$Token'");
332                         error = true;
333                         continue;
334
335                 default:
336                         break;
337                 }
338
339                 switch (static_cast<TextClassTags>(le)) {
340
341                 case TC_FORMAT:
342                         if (lexrc.next())
343                                 format = lexrc.getInteger();
344                         break;
345
346                 case TC_OUTPUTTYPE:   // output type definition
347                         readOutputType(lexrc);
348                         break;
349
350                 case TC_INPUT: // Include file
351                         if (lexrc.next()) {
352                                 string const inc = lexrc.getString();
353                                 FileName tmp = libFileSearch("layouts", inc,
354                                                             "layout");
355
356                                 if (tmp.empty()) {
357                                         lexrc.printError("Could not find input file: " + inc);
358                                         error = true;
359                                 } else if (!read(tmp, MERGE)) {
360                                         lexrc.printError("Error reading input"
361                                                          "file: " + tmp.absFilename());
362                                         error = true;
363                                 }
364                         }
365                         break;
366
367                 case TC_DEFAULTSTYLE:
368                         if (lexrc.next()) {
369                                 docstring const name = from_utf8(subst(lexrc.getString(),
370                                                           '_', ' '));
371                                 defaultlayout_ = name;
372                         }
373                         break;
374
375                 case TC_STYLE: {
376                         if (!lexrc.next()) {
377                                 lexrc.printError("No name given for style: `$$Token'.");
378                                 error = true;
379                                 break;
380                         }
381                         docstring const name = from_utf8(subst(lexrc.getString(),
382                                                         '_', ' '));
383                         if (name.empty()) {
384                                 string s = "Could not read name for style: `$$Token' "
385                                         + lexrc.getString() + " is probably not valid UTF-8!";
386                                 lexrc.printError(s.c_str());
387                                 Layout lay;
388                                 // Since we couldn't read the name, we just scan the rest
389                                 // of the style and discard it.
390                                 error = !readStyle(lexrc, lay);
391                         } else if (hasLayout(name)) {
392                                 Layout & lay = operator[](name);
393                                 error = !readStyle(lexrc, lay);
394                         } else {
395                                 Layout layout;
396                                 layout.setName(name);
397                                 error = !readStyle(lexrc, layout);
398                                 if (!error)
399                                         layoutlist_.push_back(layout);
400
401                                 if (defaultlayout_.empty()) {
402                                         // We do not have a default layout yet, so we choose
403                                         // the first layout we encounter.
404                                         defaultlayout_ = name;
405                                 }
406                         }
407                         break;
408                 }
409
410                 case TC_NOSTYLE:
411                         if (lexrc.next()) {
412                                 docstring const style = from_utf8(subst(lexrc.getString(),
413                                                      '_', ' '));
414                                 if (!deleteLayout(style))
415                                         lyxerr << "Cannot delete style `"
416                                                << to_utf8(style) << '\'' << endl;
417                         }
418                         break;
419
420                 case TC_COLUMNS:
421                         if (lexrc.next())
422                                 columns_ = lexrc.getInteger();
423                         break;
424
425                 case TC_SIDES:
426                         if (lexrc.next()) {
427                                 switch (lexrc.getInteger()) {
428                                 case 1: sides_ = OneSide; break;
429                                 case 2: sides_ = TwoSides; break;
430                                 default:
431                                         lyxerr << "Impossible number of page"
432                                                 " sides, setting to one."
433                                                << endl;
434                                         sides_ = OneSide;
435                                         break;
436                                 }
437                         }
438                         break;
439
440                 case TC_PAGESTYLE:
441                         lexrc.next();
442                         pagestyle_ = rtrim(lexrc.getString());
443                         break;
444
445                 case TC_DEFAULTFONT:
446                         defaultfont_ = lyxRead(lexrc);
447                         if (!defaultfont_.resolved()) {
448                                 lexrc.printError("Warning: defaultfont should "
449                                                  "be fully instantiated!");
450                                 defaultfont_.realize(sane_font);
451                         }
452                         break;
453
454                 case TC_SECNUMDEPTH:
455                         lexrc.next();
456                         secnumdepth_ = lexrc.getInteger();
457                         break;
458
459                 case TC_TOCDEPTH:
460                         lexrc.next();
461                         tocdepth_ = lexrc.getInteger();
462                         break;
463
464                 // First step to support options
465                 case TC_CLASSOPTIONS:
466                         readClassOptions(lexrc);
467                         break;
468
469                 case TC_PREAMBLE:
470                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
471                         break;
472
473                 case TC_ADDTOPREAMBLE:
474                         preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
475                         break;
476
477                 case TC_PROVIDES: {
478                         lexrc.next();
479                         string const feature = lexrc.getString();
480                         lexrc.next();
481                         if (lexrc.getInteger())
482                                 provides_.insert(feature);
483                         else
484                                 provides_.erase(feature);
485                         break;
486                 }
487
488                 case TC_REQUIRES: {
489                         lexrc.eatLine();
490                         vector<string> const req 
491                                 = getVectorFromString(lexrc.getString());
492                         requires_.insert(req.begin(), req.end());
493                         break;
494                 }
495
496                 case TC_DEFAULTMODULE: {
497                         lexrc.next();
498                         string const module = lexrc.getString();
499                         if (find(default_modules_.begin(), default_modules_.end(), module) == default_modules_.end())
500                                 default_modules_.push_back(module);
501                         break;
502                 }
503
504                 case TC_PROVIDESMODULE: {
505                         lexrc.next();
506                         string const module = lexrc.getString();
507                         if (find(provided_modules_.begin(), provided_modules_.end(), module) == provided_modules_.end())
508                                 provided_modules_.push_back(module);
509                         break;
510                 }
511
512                 case TC_EXCLUDESMODULE: {
513                         lexrc.next();
514                         string const module = lexrc.getString();
515                         // modules already have their own way to exclude other modules
516                         if (rt == MODULE) {
517                                 LYXERR0("ExcludesModule tag cannot be used in a module!");
518                                 break;
519                         }
520                         if (find(excluded_modules_.begin(), excluded_modules_.end(), module) == excluded_modules_.end())
521                                 excluded_modules_.push_back(module);
522                         break;
523                 }
524
525                 case TC_LEFTMARGIN:     // left margin type
526                         if (lexrc.next())
527                                 leftmargin_ = lexrc.getDocString();
528                         break;
529
530                 case TC_RIGHTMARGIN:    // right margin type
531                         if (lexrc.next())
532                                 rightmargin_ = lexrc.getDocString();
533                         break;
534
535                 case TC_INSETLAYOUT: {
536                         if (!lexrc.next()) {
537                                 lexrc.printError("No name given for InsetLayout: `$$Token'.");
538                                 error = true;
539                                 break;
540                         }
541                         docstring const name = subst(lexrc.getDocString(), '_', ' ');
542                         if (name.empty()) {
543                                 string s = "Could not read name for InsetLayout: `$$Token' "
544                                         + lexrc.getString() + " is probably not valid UTF-8!";
545                                 lexrc.printError(s.c_str());
546                                 InsetLayout il;
547                                 // Since we couldn't read the name, we just scan the rest
548                                 // of the style and discard it.
549                                 il.read(lexrc, *this);
550                                 error = true;
551                         } else if (hasInsetLayout(name)) {
552                                 InsetLayout & il = insetlayoutlist_[name];
553                                 error = !il.read(lexrc, *this);
554                         } else {
555                                 InsetLayout il;
556                                 il.setName(name);
557                                 error = !il.read(lexrc, *this);
558                                 if (!error)
559                                         insetlayoutlist_[name] = il;
560                         }
561                         break;
562                 }
563
564                 case TC_FLOAT:
565                         readFloat(lexrc);
566                         break;
567
568                 case TC_COUNTER:
569                         if (lexrc.next()) {
570                                 docstring const name = lexrc.getDocString();
571                                 if (name.empty()) {
572                                         string s = "Could not read name for counter: `$$Token' "
573                                                         + lexrc.getString() + " is probably not valid UTF-8!";
574                                         lexrc.printError(s.c_str());
575                                         Counter c;
576                                         // Since we couldn't read the name, we just scan the rest
577                                         // and discard it.
578                                         c.read(lexrc);
579                                 } else
580                                         error = !counters_.read(lexrc, name);
581                         }
582                         else {
583                                 lexrc.printError("No name given for style: `$$Token'.");
584                                 error = true;
585                         }
586                         break;
587
588                 case TC_TITLELATEXTYPE:
589                         readTitleType(lexrc);
590                         break;
591
592                 case TC_TITLELATEXNAME:
593                         if (lexrc.next())
594                                 titlename_ = lexrc.getString();
595                         break;
596
597                 case TC_NOFLOAT:
598                         if (lexrc.next()) {
599                                 string const nofloat = lexrc.getString();
600                                 floatlist_.erase(nofloat);
601                         }
602                         break;
603                 } // end of switch
604
605                 //Note that this is triggered the first time through the loop unless
606                 //we hit a format tag.
607                 if (format != FORMAT)
608                         break;
609         }
610
611         if (format != FORMAT)
612                 return FORMAT_MISMATCH;
613
614         if (rt != BASECLASS) 
615                 return (error ? ERROR : OK);
616
617         if (defaultlayout_.empty()) {
618                 LYXERR0("Error: Textclass '" << name_
619                                                 << "' is missing a defaultstyle.");
620                 error = true;
621         }
622                 
623         // Try to erase "stdinsets" from the provides_ set. 
624         // The
625         //   Provides stdinsets 1
626         // declaration simply tells us that the standard insets have been
627         // defined. (It's found in stdinsets.inc but could also be used in
628         // user-defined files.) There isn't really any such package. So we
629         // might as well go ahead and erase it.
630         // If we do not succeed, then it was not there, which means that
631         // the textclass did not provide the definitions of the standard
632         // insets. So we need to try to load them.
633         int erased = provides_.erase("stdinsets");
634         if (!erased) {
635                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
636
637                 if (tmp.empty()) {
638                         throw ExceptionMessage(WarningException, _("Missing File"),
639                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
640                         error = true;
641                 } else if (!read(tmp, MERGE)) {
642                         throw ExceptionMessage(WarningException, _("Corrupt File"),
643                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
644                         error = true;
645                 }
646         }
647
648         min_toclevel_ = Layout::NOT_IN_TOC;
649         max_toclevel_ = Layout::NOT_IN_TOC;
650         const_iterator lit = begin();
651         const_iterator len = end();
652         for (; lit != len; ++lit) {
653                 int const toclevel = lit->toclevel;
654                 if (toclevel != Layout::NOT_IN_TOC) {
655                         if (min_toclevel_ == Layout::NOT_IN_TOC)
656                                 min_toclevel_ = toclevel;
657                         else
658                                 min_toclevel_ = min(min_toclevel_, toclevel);
659                         max_toclevel_ = max(max_toclevel_, toclevel);
660                 }
661         }
662         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
663                 << ", maximum is " << max_toclevel_);
664
665         return (error ? ERROR : OK);
666 }
667
668
669 void TextClass::readTitleType(Lexer & lexrc)
670 {
671         LexerKeyword titleTypeTags[] = {
672                 { "commandafter", TITLE_COMMAND_AFTER },
673                 { "environment",  TITLE_ENVIRONMENT }
674         };
675
676         PushPopHelper pph(lexrc, titleTypeTags);
677
678         int le = lexrc.lex();
679         switch (le) {
680         case Lexer::LEX_UNDEF:
681                 lexrc.printError("Unknown output type `$$Token'");
682                 break;
683         case TITLE_COMMAND_AFTER:
684         case TITLE_ENVIRONMENT:
685                 titletype_ = static_cast<TitleLatexType>(le);
686                 break;
687         default:
688                 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
689                 break;
690         }
691 }
692
693
694 void TextClass::readOutputType(Lexer & lexrc)
695 {
696         LexerKeyword outputTypeTags[] = {
697                 { "docbook",  DOCBOOK },
698                 { "latex",    LATEX },
699                 { "literate", LITERATE }
700         };
701
702         PushPopHelper pph(lexrc, outputTypeTags);
703
704         int le = lexrc.lex();
705         switch (le) {
706         case Lexer::LEX_UNDEF:
707                 lexrc.printError("Unknown output type `$$Token'");
708                 return;
709         case LATEX:
710         case DOCBOOK:
711         case LITERATE:
712                 outputType_ = static_cast<OutputType>(le);
713                 break;
714         default:
715                 LYXERR0("Unhandled value " << le);
716                 break;
717         }
718 }
719
720
721 void TextClass::readClassOptions(Lexer & lexrc)
722 {
723         enum {
724                 CO_FONTSIZE = 1,
725                 CO_PAGESTYLE,
726                 CO_OTHER,
727                 CO_HEADER,
728                 CO_END
729         };
730
731         LexerKeyword classOptionsTags[] = {
732                 {"end",       CO_END },
733                 {"fontsize",  CO_FONTSIZE },
734                 {"header",    CO_HEADER },
735                 {"other",     CO_OTHER },
736                 {"pagestyle", CO_PAGESTYLE }
737         };
738
739         lexrc.pushTable(classOptionsTags);
740         bool getout = false;
741         while (!getout && lexrc.isOK()) {
742                 int le = lexrc.lex();
743                 switch (le) {
744                 case Lexer::LEX_UNDEF:
745                         lexrc.printError("Unknown ClassOption tag `$$Token'");
746                         continue;
747                 default: break;
748                 }
749                 switch (le) {
750                 case CO_FONTSIZE:
751                         lexrc.next();
752                         opt_fontsize_ = rtrim(lexrc.getString());
753                         break;
754                 case CO_PAGESTYLE:
755                         lexrc.next();
756                         opt_pagestyle_ = rtrim(lexrc.getString());
757                         break;
758                 case CO_OTHER:
759                         lexrc.next();
760                         options_ = lexrc.getString();
761                         break;
762                 case CO_HEADER:
763                         lexrc.next();
764                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
765                         break;
766                 case CO_END:
767                         getout = true;
768                         break;
769                 }
770         }
771         lexrc.popTable();
772 }
773
774
775 void TextClass::readFloat(Lexer & lexrc)
776 {
777         enum {
778                 FT_TYPE = 1,
779                 FT_NAME,
780                 FT_PLACEMENT,
781                 FT_EXT,
782                 FT_WITHIN,
783                 FT_STYLE,
784                 FT_LISTNAME,
785                 FT_BUILTIN,
786                 FT_END
787         };
788
789         LexerKeyword floatTags[] = {
790                 { "end", FT_END },
791                 { "extension", FT_EXT },
792                 { "guiname", FT_NAME },
793                 { "latexbuiltin", FT_BUILTIN },
794                 { "listname", FT_LISTNAME },
795                 { "numberwithin", FT_WITHIN },
796                 { "placement", FT_PLACEMENT },
797                 { "style", FT_STYLE },
798                 { "type", FT_TYPE }
799         };
800
801         lexrc.pushTable(floatTags);
802
803         string type;
804         string placement;
805         string ext;
806         string within;
807         string style;
808         string name;
809         string listName;
810         bool builtin = false;
811
812         bool getout = false;
813         while (!getout && lexrc.isOK()) {
814                 int le = lexrc.lex();
815                 switch (le) {
816                 case Lexer::LEX_UNDEF:
817                         lexrc.printError("Unknown float tag `$$Token'");
818                         continue;
819                 default: break;
820                 }
821                 switch (le) {
822                 case FT_TYPE:
823                         lexrc.next();
824                         type = lexrc.getString();
825                         if (floatlist_.typeExist(type)) {
826                                 Floating const & fl = floatlist_.getType(type);
827                                 placement = fl.placement();
828                                 ext = fl.ext();
829                                 within = fl.within();
830                                 style = fl.style();
831                                 name = fl.name();
832                                 listName = fl.listName();
833                                 builtin = fl.builtin();
834                         } 
835                         break;
836                 case FT_NAME:
837                         lexrc.next();
838                         name = lexrc.getString();
839                         break;
840                 case FT_PLACEMENT:
841                         lexrc.next();
842                         placement = lexrc.getString();
843                         break;
844                 case FT_EXT:
845                         lexrc.next();
846                         ext = lexrc.getString();
847                         break;
848                 case FT_WITHIN:
849                         lexrc.next();
850                         within = lexrc.getString();
851                         if (within == "none")
852                                 within.erase();
853                         break;
854                 case FT_STYLE:
855                         lexrc.next();
856                         style = lexrc.getString();
857                         break;
858                 case FT_LISTNAME:
859                         lexrc.next();
860                         listName = lexrc.getString();
861                         break;
862                 case FT_BUILTIN:
863                         lexrc.next();
864                         builtin = lexrc.getBool();
865                         break;
866                 case FT_END:
867                         getout = true;
868                         break;
869                 }
870         }
871
872         // Here if have a full float if getout == true
873         if (getout) {
874                 Floating fl(type, placement, ext, within,
875                             style, name, listName, builtin);
876                 floatlist_.newFloat(fl);
877                 // each float has its own counter
878                 counters_.newCounter(from_ascii(type), from_ascii(within),
879                                       docstring(), docstring());
880                 // also define sub-float counters
881                 docstring const subtype = "sub-" + from_ascii(type);
882                 counters_.newCounter(subtype, from_ascii(type),
883                                       "\\alph{" + subtype + "}", docstring());
884         }
885
886         lexrc.popTable();
887 }
888
889
890 bool TextClass::hasLayout(docstring const & n) const
891 {
892         docstring const name = n.empty() ? defaultLayoutName() : n;
893
894         return find_if(layoutlist_.begin(), layoutlist_.end(),
895                        LayoutNamesEqual(name))
896                 != layoutlist_.end();
897 }
898
899
900 bool TextClass::hasInsetLayout(docstring const & n) const
901 {
902         if (n.empty()) 
903                 return false;
904         InsetLayouts::const_iterator it = insetlayoutlist_.begin();
905         InsetLayouts::const_iterator en = insetlayoutlist_.end();
906         for (; it != en; ++it)
907                 if (n == it->first)
908                         return true;
909         return false;
910 }
911
912
913 Layout const & TextClass::operator[](docstring const & name) const
914 {
915         LASSERT(!name.empty(), /**/);
916
917         const_iterator it = 
918                 find_if(begin(), end(), LayoutNamesEqual(name));
919
920         if (it == end()) {
921                 lyxerr << "We failed to find the layout '" << to_utf8(name)
922                        << "' in the layout list. You MUST investigate!"
923                        << endl;
924                 for (const_iterator cit = begin(); cit != end(); ++cit)
925                         lyxerr  << " " << to_utf8(cit->name()) << endl;
926
927                 // we require the name to exist
928                 LASSERT(false, /**/);
929         }
930
931         return *it;
932 }
933
934
935 Layout & TextClass::operator[](docstring const & name)
936 {
937         LASSERT(!name.empty(), /**/);
938
939         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
940
941         if (it == end()) {
942                 LYXERR0("We failed to find the layout '" << to_utf8(name)
943                        << "' in the layout list. You MUST investigate!");
944                 for (const_iterator cit = begin(); cit != end(); ++cit)
945                         LYXERR0(" " << to_utf8(cit->name()));
946
947                 // we require the name to exist
948                 LASSERT(false, /**/);
949         }
950
951         return *it;
952 }
953
954
955 bool TextClass::deleteLayout(docstring const & name)
956 {
957         if (name == defaultLayoutName() || name == plainLayoutName())
958                 return false;
959
960         LayoutList::iterator it =
961                 remove_if(layoutlist_.begin(), layoutlist_.end(),
962                           LayoutNamesEqual(name));
963
964         LayoutList::iterator end = layoutlist_.end();
965         bool const ret = (it != end);
966         layoutlist_.erase(it, end);
967         return ret;
968 }
969
970
971 // Load textclass info if not loaded yet
972 bool TextClass::load(string const & path) const
973 {
974         if (loaded_)
975                 return true;
976
977         // Read style-file, provided path is searched before the system ones
978         // If path is a file, it is loaded directly.
979         FileName layout_file(path);
980         if (!path.empty() && !layout_file.isReadableFile())
981                 layout_file = FileName(addName(path, name_ + ".layout"));
982         if (layout_file.empty() || !layout_file.exists())
983                 layout_file = libFileSearch("layouts", name_, "layout");
984         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
985
986         if (!loaded_) {
987                 lyxerr << "Error reading `"
988                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
989                        << "'\n(Check `" << name_
990                        << "')\nCheck your installation and "
991                         "try Options/Reconfigure..." << endl;
992         }
993
994         return loaded_;
995 }
996
997
998 void DocumentClass::addLayoutIfNeeded(docstring const & n) const
999 {
1000         if (!hasLayout(n))
1001                 layoutlist_.push_back(createBasicLayout(n, true));
1002 }
1003
1004
1005 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
1006 {
1007         // FIXME The fix for the InsetLayout part of 4812 would be here:
1008         // Add the InsetLayout to the document class if it is not found.
1009         docstring n = name;
1010         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1011         while (!n.empty()) {
1012                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1013                 if (cit != cen && cit->first == n)
1014                         return cit->second;
1015                 size_t i = n.find(':');
1016                 if (i == string::npos)
1017                         break;
1018                 n = n.substr(0, i);
1019         }
1020         return plain_insetlayout_;
1021 }
1022
1023
1024 docstring const & TextClass::defaultLayoutName() const
1025 {
1026         // This really should come from the actual layout... (Lgb)
1027         return defaultlayout_;
1028 }
1029
1030
1031 Layout const & TextClass::defaultLayout() const
1032 {
1033         return operator[](defaultLayoutName());
1034 }
1035
1036
1037 bool TextClass::isDefaultLayout(Layout const & layout) const 
1038 {
1039         return layout.name() == defaultLayoutName();
1040 }
1041
1042
1043 bool TextClass::isPlainLayout(Layout const & layout) const 
1044 {
1045         return layout.name() == plainLayoutName();
1046 }
1047
1048
1049 Layout TextClass::createBasicLayout(docstring const & name, bool unknown) const
1050 {
1051         static Layout * defaultLayout = NULL;
1052
1053         if (defaultLayout) {
1054                 defaultLayout->setUnknown(unknown);
1055                 defaultLayout->setName(name);
1056                 return *defaultLayout;
1057         }
1058
1059         static char const * s = "Margin Static\n"
1060                         "LatexType Paragraph\n"
1061                         "LatexName dummy\n"
1062                         "Align Block\n"
1063                         "AlignPossible Left, Right, Center\n"
1064                         "LabelType No_Label\n"
1065                         "End";
1066         istringstream ss(s);
1067         Lexer lex(textClassTags);
1068         lex.setStream(ss);
1069         defaultLayout = new Layout;
1070         defaultLayout->setUnknown(unknown);
1071         defaultLayout->setName(name);
1072         if (!readStyle(lex, *defaultLayout)) {
1073                 // The only way this happens is because the hardcoded layout above
1074                 // is wrong.
1075                 LASSERT(false, /**/);
1076         };
1077         return *defaultLayout;
1078 }
1079
1080 /////////////////////////////////////////////////////////////////////////
1081 //
1082 // DocumentClassBundle
1083 //
1084 /////////////////////////////////////////////////////////////////////////
1085
1086 DocumentClassBundle::~DocumentClassBundle()
1087 {
1088         for (size_t i = 0; i != documentClasses_.size(); ++i)
1089                 delete documentClasses_[i];
1090         documentClasses_.clear();
1091 }
1092
1093 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1094 {
1095         DocumentClass * dc = new DocumentClass(baseClass);
1096         documentClasses_.push_back(dc);
1097         return *documentClasses_.back();
1098 }
1099
1100
1101 DocumentClassBundle & DocumentClassBundle::get()
1102 {
1103         static DocumentClassBundle singleton; 
1104         return singleton; 
1105 }
1106
1107
1108 /////////////////////////////////////////////////////////////////////////
1109 //
1110 // DocumentClass
1111 //
1112 /////////////////////////////////////////////////////////////////////////
1113
1114 DocumentClass::DocumentClass(LayoutFile const & tc)
1115         : TextClass(tc)
1116 {}
1117
1118
1119 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1120 {
1121         LayoutList::const_iterator it  = layoutlist_.begin();
1122         LayoutList::const_iterator end = layoutlist_.end();
1123         for (; it != end; ++it)
1124                 if (it->latexname() == lay)
1125                         return true;
1126         return false;
1127 }
1128
1129
1130 bool DocumentClass::provides(string const & p) const
1131 {
1132         return provides_.find(p) != provides_.end();
1133 }
1134
1135
1136 bool DocumentClass::hasTocLevels() const
1137 {
1138         return min_toclevel_ != Layout::NOT_IN_TOC;
1139 }
1140
1141
1142 /////////////////////////////////////////////////////////////////////////
1143 //
1144 // PageSides
1145 //
1146 /////////////////////////////////////////////////////////////////////////
1147
1148 ostream & operator<<(ostream & os, PageSides p)
1149 {
1150         switch (p) {
1151         case OneSide:
1152                 os << '1';
1153                 break;
1154         case TwoSides:
1155                 os << '2';
1156                 break;
1157         }
1158         return os;
1159 }
1160
1161
1162 } // namespace lyx