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