]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
f7da2d11f2876a96e94dccb6753472e75f46f81a
[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         LexerKeyword 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);
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
264         Lexer lexrc(textClassTags);
265         lexrc.setFile(filename);
266         ReturnValues retval = read(lexrc, rt);
267         
268         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
269                         to_utf8(makeDisplayPath(filename.absFilename())));
270         
271         if (retval != FORMAT_MISMATCH) 
272                 return retval == OK;
273         
274         bool const worx = convertLayoutFormat(filename, rt);
275         if (!worx) {
276                 lyxerr << "Unable to convert " << filename << 
277                         " to format " << FORMAT << std::endl;
278                 return false;
279         }
280         return true;
281 }
282
283
284 bool TextClass::validate(std::string const & str)
285 {
286         TextClass tc;
287         return tc.read(str, VALIDATION);
288 }
289
290
291 bool TextClass::read(std::string const & str, ReadType rt) 
292 {
293         Lexer lexrc(textClassTags);
294         istringstream is(str);
295         lexrc.setStream(is);
296         ReturnValues retval = read(lexrc, rt);
297
298         if (retval != FORMAT_MISMATCH) 
299                 return retval == OK;
300
301         // write the layout string to a temporary file
302         FileName const tempfile = FileName::tempName();
303         ofstream os(tempfile.toFilesystemEncoding().c_str());
304         if (!os) {
305                 lyxerr << "Unable to create tempoary file in TextClass::read!!" 
306                         << std::endl;
307                 return false;
308         }
309         os << str;
310         os.close();
311
312         // now try to convert it
313         bool const worx = convertLayoutFormat(tempfile, rt);
314         if (!worx) {
315                 lyxerr << "Unable to convert internal layout information to format " 
316                         << FORMAT << std::endl;
317         }
318         tempfile.removeFile();
319         return worx;
320 }
321
322
323 // Reads a textclass structure from file.
324 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt) 
325 {
326         bool error = !lexrc.isOK();
327
328         // Format of files before the 'Format' tag was introduced
329         int format = 1;
330
331         // parsing
332         while (lexrc.isOK() && !error) {
333                 int le = lexrc.lex();
334
335                 switch (le) {
336                 case Lexer::LEX_FEOF:
337                         continue;
338
339                 case Lexer::LEX_UNDEF:
340                         lexrc.printError("Unknown TextClass tag `$$Token'");
341                         error = true;
342                         continue;
343
344                 default:
345                         break;
346                 }
347
348                 switch (static_cast<TextClassTags>(le)) {
349
350                 case TC_FORMAT:
351                         if (lexrc.next())
352                                 format = lexrc.getInteger();
353                         break;
354
355                 case TC_OUTPUTTYPE:   // output type definition
356                         readOutputType(lexrc);
357                         break;
358
359                 case TC_INPUT: // Include file
360                         if (lexrc.next()) {
361                                 string const inc = lexrc.getString();
362                                 FileName tmp = libFileSearch("layouts", inc,
363                                                             "layout");
364
365                                 if (tmp.empty()) {
366                                         lexrc.printError("Could not find input file: " + inc);
367                                         error = true;
368                                 } else if (!read(tmp, MERGE)) {
369                                         lexrc.printError("Error reading input"
370                                                          "file: " + tmp.absFilename());
371                                         error = true;
372                                 }
373                         }
374                         break;
375
376                 case TC_DEFAULTSTYLE:
377                         if (lexrc.next()) {
378                                 docstring const name = from_utf8(subst(lexrc.getString(),
379                                                           '_', ' '));
380                                 defaultlayout_ = name;
381                         }
382                         break;
383
384                 case TC_ENVIRONMENT:
385                 case TC_STYLE:
386                         if (lexrc.next()) {
387                                 docstring const name = from_utf8(subst(lexrc.getString(),
388                                                     '_', ' '));
389                                 if (name.empty()) {
390                                         string s = "Could not read name for style: `$$Token' "
391                                                 + lexrc.getString() + " is probably not valid UTF-8!";
392                                         lexrc.printError(s.c_str());
393                                         Layout lay;
394                                         // Since we couldn't read the name, we just scan the rest
395                                         // of the style and discard it.
396                                         error = !readStyle(lexrc, lay);
397                                 } else if (hasLayout(name)) {
398                                         Layout & lay = operator[](name);
399                                         error = !readStyle(lexrc, lay);
400                                 } else {
401                                         Layout lay;
402                                         lay.setName(name);
403                                         if (le == TC_ENVIRONMENT)
404                                                 lay.is_environment = true;
405                                         error = !readStyle(lexrc, lay);
406                                         if (!error)
407                                                 layoutlist_.push_back(lay);
408
409                                         if (defaultlayout_.empty()) {
410                                                 // We do not have a default layout yet, so we choose
411                                                 // the first layout we encounter.
412                                                 defaultlayout_ = name;
413                                         }
414                                 }
415                         }
416                         else {
417                                 //FIXME Should we also eat the style here? viz:
418                                 //Layout lay;
419                                 //readStyle(lexrc, lay);
420                                 //as above...
421                                 lexrc.printError("No name given for style: `$$Token'.");
422                                 error = true;
423                         }
424                         break;
425
426                 case TC_NOSTYLE:
427                         if (lexrc.next()) {
428                                 docstring const style = from_utf8(subst(lexrc.getString(),
429                                                      '_', ' '));
430                                 if (!deleteLayout(style))
431                                         lyxerr << "Cannot delete style `"
432                                                << to_utf8(style) << '\'' << endl;
433                         }
434                         break;
435
436                 case TC_COLUMNS:
437                         if (lexrc.next())
438                                 columns_ = lexrc.getInteger();
439                         break;
440
441                 case TC_SIDES:
442                         if (lexrc.next()) {
443                                 switch (lexrc.getInteger()) {
444                                 case 1: sides_ = OneSide; break;
445                                 case 2: sides_ = TwoSides; break;
446                                 default:
447                                         lyxerr << "Impossible number of page"
448                                                 " sides, setting to one."
449                                                << endl;
450                                         sides_ = OneSide;
451                                         break;
452                                 }
453                         }
454                         break;
455
456                 case TC_PAGESTYLE:
457                         lexrc.next();
458                         pagestyle_ = rtrim(lexrc.getString());
459                         break;
460
461                 case TC_DEFAULTFONT:
462                         defaultfont_ = lyxRead(lexrc);
463                         if (!defaultfont_.resolved()) {
464                                 lexrc.printError("Warning: defaultfont should "
465                                                  "be fully instantiated!");
466                                 defaultfont_.realize(sane_font);
467                         }
468                         break;
469
470                 case TC_SECNUMDEPTH:
471                         lexrc.next();
472                         secnumdepth_ = lexrc.getInteger();
473                         break;
474
475                 case TC_TOCDEPTH:
476                         lexrc.next();
477                         tocdepth_ = lexrc.getInteger();
478                         break;
479
480                 // First step to support options
481                 case TC_CLASSOPTIONS:
482                         readClassOptions(lexrc);
483                         break;
484
485                 case TC_PREAMBLE:
486                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
487                         break;
488
489                 case TC_ADDTOPREAMBLE:
490                         preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
491                         break;
492
493                 case TC_PROVIDES: {
494                         lexrc.next();
495                         string const feature = lexrc.getString();
496                         lexrc.next();
497                         if (lexrc.getInteger())
498                                 provides_.insert(feature);
499                         else
500                                 provides_.erase(feature);
501                         break;
502                 }
503
504                 case TC_REQUIRES: {
505                         lexrc.eatLine();
506                         vector<string> const req 
507                                 = getVectorFromString(lexrc.getString());
508                         requires_.insert(req.begin(), req.end());
509                         break;
510                 }
511
512                 case TC_LEFTMARGIN:     // left margin type
513                         if (lexrc.next())
514                                 leftmargin_ = lexrc.getDocString();
515                         break;
516
517                 case TC_RIGHTMARGIN:    // right margin type
518                         if (lexrc.next())
519                                 rightmargin_ = lexrc.getDocString();
520                         break;
521
522                 case TC_INSETLAYOUT:
523                         if (lexrc.next()) {
524                                 InsetLayout il;
525                                 if (il.read(lexrc)) {
526                                         insetlayoutlist_[il.name()] = il;
527                                 }
528                                 // else there was an error, so forget it
529                         }
530                         break;
531
532                 case TC_FLOAT:
533                         readFloat(lexrc);
534                         break;
535
536                 case TC_COUNTER:
537                         readCounter(lexrc);
538                         break;
539
540                 case TC_TITLELATEXTYPE:
541                         readTitleType(lexrc);
542                         break;
543
544                 case TC_TITLELATEXNAME:
545                         if (lexrc.next())
546                                 titlename_ = lexrc.getString();
547                         break;
548
549                 case TC_NOFLOAT:
550                         if (lexrc.next()) {
551                                 string const nofloat = lexrc.getString();
552                                 floatlist_.erase(nofloat);
553                         }
554                         break;
555                 }
556
557                 //Note that this is triggered the first time through the loop unless
558                 //we hit a format tag.
559                 if (format != FORMAT)
560                         break;
561         }
562
563         if (format != FORMAT)
564                 return FORMAT_MISMATCH;
565
566         if (rt != BASECLASS) 
567                 return (error ? ERROR : OK);
568
569         if (defaultlayout_.empty()) {
570                 lyxerr << "Error: Textclass '" << name_
571                                                 << "' is missing a defaultstyle." << endl;
572                 error = true;
573         }
574                 
575         //Try to erase "stdinsets" from the provides_ set. 
576         //The
577         //  Provides stdinsets 1
578         //declaration simply tells us that the standard insets have been
579         //defined. (It's found in stdinsets.inc but could also be used in
580         //user-defined files.) There isn't really any such package. So we
581         //might as well go ahead and erase it.
582         //If we do not succeed, then it was not there, which means that
583         //the textclass did not provide the definitions of the standard
584         //insets. So we need to try to load them.
585         int erased = provides_.erase("stdinsets");
586         if (!erased) {
587                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
588
589                 if (tmp.empty()) {
590                         throw ExceptionMessage(WarningException, _("Missing File"),
591                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
592                         error = true;
593                 } else if (!read(tmp, MERGE)) {
594                         throw ExceptionMessage(WarningException, _("Corrupt File"),
595                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
596                         error = true;
597                 }
598         }
599
600         min_toclevel_ = Layout::NOT_IN_TOC;
601         max_toclevel_ = Layout::NOT_IN_TOC;
602         const_iterator lit = begin();
603         const_iterator len = end();
604         for (; lit != len; ++lit) {
605                 int const toclevel = lit->toclevel;
606                 if (toclevel != Layout::NOT_IN_TOC) {
607                         if (min_toclevel_ == Layout::NOT_IN_TOC)
608                                 min_toclevel_ = toclevel;
609                         else
610                                 min_toclevel_ = min(min_toclevel_, toclevel);
611                         max_toclevel_ = max(max_toclevel_, toclevel);
612                 }
613         }
614         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
615                 << ", maximum is " << max_toclevel_);
616
617         return (error ? ERROR : OK);
618 }
619
620
621 void TextClass::readTitleType(Lexer & lexrc)
622 {
623         LexerKeyword titleTypeTags[] = {
624                 { "commandafter", TITLE_COMMAND_AFTER },
625                 { "environment",  TITLE_ENVIRONMENT }
626         };
627
628         PushPopHelper pph(lexrc, titleTypeTags);
629
630         int le = lexrc.lex();
631         switch (le) {
632         case Lexer::LEX_UNDEF:
633                 lexrc.printError("Unknown output type `$$Token'");
634                 return;
635         case TITLE_COMMAND_AFTER:
636         case TITLE_ENVIRONMENT:
637                 titletype_ = static_cast<TitleLatexType>(le);
638                 break;
639         default:
640                 lyxerr << "Unhandled value " << le
641                        << " in TextClass::readTitleType." << endl;
642
643                 break;
644         }
645 }
646
647
648 void TextClass::readOutputType(Lexer & lexrc)
649 {
650         LexerKeyword outputTypeTags[] = {
651                 { "docbook",  DOCBOOK },
652                 { "latex",    LATEX },
653                 { "literate", LITERATE }
654         };
655
656         PushPopHelper pph(lexrc, outputTypeTags);
657
658         int le = lexrc.lex();
659         switch (le) {
660         case Lexer::LEX_UNDEF:
661                 lexrc.printError("Unknown output type `$$Token'");
662                 return;
663         case LATEX:
664         case DOCBOOK:
665         case LITERATE:
666                 outputType_ = static_cast<OutputType>(le);
667                 break;
668         default:
669                 lyxerr << "Unhandled value " << le
670                        << " in TextClass::readOutputType." << endl;
671
672                 break;
673         }
674 }
675
676
677 void TextClass::readClassOptions(Lexer & lexrc)
678 {
679         enum {
680                 CO_FONTSIZE = 1,
681                 CO_PAGESTYLE,
682                 CO_OTHER,
683                 CO_HEADER,
684                 CO_END
685         };
686
687         LexerKeyword classOptionsTags[] = {
688                 {"end",       CO_END },
689                 {"fontsize",  CO_FONTSIZE },
690                 {"header",    CO_HEADER },
691                 {"other",     CO_OTHER },
692                 {"pagestyle", CO_PAGESTYLE }
693         };
694
695         lexrc.pushTable(classOptionsTags);
696         bool getout = false;
697         while (!getout && lexrc.isOK()) {
698                 int le = lexrc.lex();
699                 switch (le) {
700                 case Lexer::LEX_UNDEF:
701                         lexrc.printError("Unknown ClassOption tag `$$Token'");
702                         continue;
703                 default: break;
704                 }
705                 switch (le) {
706                 case CO_FONTSIZE:
707                         lexrc.next();
708                         opt_fontsize_ = rtrim(lexrc.getString());
709                         break;
710                 case CO_PAGESTYLE:
711                         lexrc.next();
712                         opt_pagestyle_ = rtrim(lexrc.getString());
713                         break;
714                 case CO_OTHER:
715                         lexrc.next();
716                         options_ = lexrc.getString();
717                         break;
718                 case CO_HEADER:
719                         lexrc.next();
720                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
721                         break;
722                 case CO_END:
723                         getout = true;
724                         break;
725                 }
726         }
727         lexrc.popTable();
728 }
729
730
731 void TextClass::readFloat(Lexer & lexrc)
732 {
733         enum {
734                 FT_TYPE = 1,
735                 FT_NAME,
736                 FT_PLACEMENT,
737                 FT_EXT,
738                 FT_WITHIN,
739                 FT_STYLE,
740                 FT_LISTNAME,
741                 FT_BUILTIN,
742                 FT_END
743         };
744
745         LexerKeyword floatTags[] = {
746                 { "end", FT_END },
747                 { "extension", FT_EXT },
748                 { "guiname", FT_NAME },
749                 { "latexbuiltin", FT_BUILTIN },
750                 { "listname", FT_LISTNAME },
751                 { "numberwithin", FT_WITHIN },
752                 { "placement", FT_PLACEMENT },
753                 { "style", FT_STYLE },
754                 { "type", FT_TYPE }
755         };
756
757         lexrc.pushTable(floatTags);
758
759         string type;
760         string placement;
761         string ext;
762         string within;
763         string style;
764         string name;
765         string listName;
766         bool builtin = false;
767
768         bool getout = false;
769         while (!getout && lexrc.isOK()) {
770                 int le = lexrc.lex();
771                 switch (le) {
772                 case Lexer::LEX_UNDEF:
773                         lexrc.printError("Unknown float tag `$$Token'");
774                         continue;
775                 default: break;
776                 }
777                 switch (le) {
778                 case FT_TYPE:
779                         lexrc.next();
780                         type = lexrc.getString();
781                         if (floatlist_.typeExist(type)) {
782                                 Floating const & fl = floatlist_.getType(type);
783                                 placement = fl.placement();
784                                 ext = fl.ext();
785                                 within = fl.within();
786                                 style = fl.style();
787                                 name = fl.name();
788                                 listName = fl.listName();
789                                 builtin = fl.builtin();
790                         } 
791                         break;
792                 case FT_NAME:
793                         lexrc.next();
794                         name = lexrc.getString();
795                         break;
796                 case FT_PLACEMENT:
797                         lexrc.next();
798                         placement = lexrc.getString();
799                         break;
800                 case FT_EXT:
801                         lexrc.next();
802                         ext = lexrc.getString();
803                         break;
804                 case FT_WITHIN:
805                         lexrc.next();
806                         within = lexrc.getString();
807                         if (within == "none")
808                                 within.erase();
809                         break;
810                 case FT_STYLE:
811                         lexrc.next();
812                         style = lexrc.getString();
813                         break;
814                 case FT_LISTNAME:
815                         lexrc.next();
816                         listName = lexrc.getString();
817                         break;
818                 case FT_BUILTIN:
819                         lexrc.next();
820                         builtin = lexrc.getBool();
821                         break;
822                 case FT_END:
823                         getout = true;
824                         break;
825                 }
826         }
827
828         // Here if have a full float if getout == true
829         if (getout) {
830                 Floating fl(type, placement, ext, within,
831                             style, name, listName, builtin);
832                 floatlist_.newFloat(fl);
833                 // each float has its own counter
834                 counters_.newCounter(from_ascii(type), from_ascii(within),
835                                       docstring(), docstring());
836                 // also define sub-float counters
837                 docstring const subtype = "sub-" + from_ascii(type);
838                 counters_.newCounter(subtype, from_ascii(type),
839                                       "\\alph{" + subtype + "}", docstring());
840         }
841
842         lexrc.popTable();
843 }
844
845
846 void TextClass::readCounter(Lexer & lexrc)
847 {
848         enum {
849                 CT_NAME = 1,
850                 CT_WITHIN,
851                 CT_LABELSTRING,
852                 CT_LABELSTRING_APPENDIX,
853                 CT_END
854         };
855
856         LexerKeyword counterTags[] = {
857                 { "end", CT_END },
858                 { "labelstring", CT_LABELSTRING },
859                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
860                 { "name", CT_NAME },
861                 { "within", CT_WITHIN }
862         };
863
864         lexrc.pushTable(counterTags);
865
866         docstring name;
867         docstring within;
868         docstring labelstring;
869         docstring labelstring_appendix;
870
871         bool getout = false;
872         while (!getout && lexrc.isOK()) {
873                 int le = lexrc.lex();
874                 switch (le) {
875                 case Lexer::LEX_UNDEF:
876                         lexrc.printError("Unknown counter tag `$$Token'");
877                         continue;
878                 default: break;
879                 }
880                 switch (le) {
881                 case CT_NAME:
882                         lexrc.next();
883                         name = lexrc.getDocString();
884                         if (counters_.hasCounter(name))
885                                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
886                         else
887                                 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
888                         break;
889                 case CT_WITHIN:
890                         lexrc.next();
891                         within = lexrc.getDocString();
892                         if (within == "none")
893                                 within.erase();
894                         break;
895                 case CT_LABELSTRING:
896                         lexrc.next();
897                         labelstring = lexrc.getDocString();
898                         labelstring_appendix = labelstring;
899                         break;
900                 case CT_LABELSTRING_APPENDIX:
901                         lexrc.next();
902                         labelstring_appendix = lexrc.getDocString();
903                         break;
904                 case CT_END:
905                         getout = true;
906                         break;
907                 }
908         }
909
910         // Here if have a full counter if getout == true
911         if (getout)
912                 counters_.newCounter(name, within, 
913                                       labelstring, labelstring_appendix);
914
915         lexrc.popTable();
916 }
917
918
919 bool TextClass::hasLayout(docstring const & n) const
920 {
921         docstring const name = n.empty() ? defaultLayoutName() : n;
922
923         return find_if(layoutlist_.begin(), layoutlist_.end(),
924                        LayoutNamesEqual(name))
925                 != layoutlist_.end();
926 }
927
928
929
930 Layout const & TextClass::operator[](docstring const & name) const
931 {
932         BOOST_ASSERT(!name.empty());
933
934         const_iterator it = 
935                 find_if(begin(), end(), LayoutNamesEqual(name));
936
937         if (it == end()) {
938                 lyxerr << "We failed to find the layout '" << to_utf8(name)
939                        << "' in the layout list. You MUST investigate!"
940                        << endl;
941                 for (const_iterator cit = begin(); cit != end(); ++cit)
942                         lyxerr  << " " << to_utf8(cit->name()) << endl;
943
944                 // we require the name to exist
945                 BOOST_ASSERT(false);
946         }
947
948         return *it;
949 }
950
951
952 Layout & TextClass::operator[](docstring const & name)
953 {
954         BOOST_ASSERT(!name.empty());
955
956         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
957
958         if (it == end()) {
959                 lyxerr << "We failed to find the layout '" << to_utf8(name)
960                        << "' in the layout list. You MUST investigate!"
961                        << endl;
962                 for (const_iterator cit = begin(); cit != end(); ++cit)
963                         lyxerr  << " " << to_utf8(cit->name()) << endl;
964
965                 // we require the name to exist
966                 BOOST_ASSERT(false);
967         }
968
969         return *it;
970 }
971
972
973 bool TextClass::deleteLayout(docstring const & name)
974 {
975         if (name == defaultLayoutName() || name == emptyLayoutName())
976                 return false;
977
978         LayoutList::iterator it =
979                 remove_if(layoutlist_.begin(), layoutlist_.end(),
980                           LayoutNamesEqual(name));
981
982         LayoutList::iterator end = layoutlist_.end();
983         bool const ret = (it != end);
984         layoutlist_.erase(it, end);
985         return ret;
986 }
987
988
989 // Load textclass info if not loaded yet
990 bool TextClass::load(string const & path) const
991 {
992         if (loaded_)
993                 return true;
994
995         // Read style-file, provided path is searched before the system ones
996         FileName layout_file;
997         if (!path.empty())
998                 layout_file = FileName(addName(path, name_ + ".layout"));
999         if (layout_file.empty() || !layout_file.exists())
1000                 layout_file = libFileSearch("layouts", name_, "layout");
1001         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1002
1003         if (!loaded_) {
1004                 lyxerr << "Error reading `"
1005                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
1006                        << "'\n(Check `" << name_
1007                        << "')\nCheck your installation and "
1008                         "try Options/Reconfigure..." << endl;
1009         }
1010
1011         return loaded_;
1012 }
1013
1014
1015 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
1016 {
1017         docstring n = name;
1018         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1019         while (!n.empty()) {
1020                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1021                 if (cit != cen && cit->first == n)
1022                         return cit->second;
1023                 size_t i = n.find(':');
1024                 if (i == string::npos)
1025                         break;
1026                 n = n.substr(0,i);
1027         }
1028         return empty_insetlayout_;
1029 }
1030
1031
1032 docstring const & TextClass::defaultLayoutName() const
1033 {
1034         // This really should come from the actual layout... (Lgb)
1035         return defaultlayout_;
1036 }
1037
1038
1039 Layout const & TextClass::defaultLayout() const
1040 {
1041         return operator[](defaultLayoutName());
1042 }
1043
1044
1045 bool TextClass::isDefaultLayout(Layout const & lay) const 
1046 {
1047         return lay.name() == defaultLayoutName();
1048 }
1049
1050
1051 bool TextClass::isEmptyLayout(Layout const & lay) const 
1052 {
1053         return lay.name() == emptyLayoutName();
1054 }
1055
1056
1057 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1058 {
1059         DocumentClass * dc = new DocumentClass(baseClass);
1060         tc_list_.push_back(dc);
1061         return *tc_list_.back();
1062 }
1063
1064
1065 DocumentClassBundle & DocumentClassBundle::get()
1066 {
1067         static DocumentClassBundle singleton; 
1068         return singleton; 
1069 }
1070
1071
1072 DocumentClass::DocumentClass(LayoutFile const & tc)
1073         : TextClass(tc)
1074 {}
1075
1076
1077 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1078 {
1079         LayoutList::const_iterator it  = layoutlist_.begin();
1080         LayoutList::const_iterator end = layoutlist_.end();
1081         for (; it != end; ++it)
1082                 if (it->latexname() == lay)
1083                         return true;
1084         return false;
1085 }
1086
1087
1088 bool DocumentClass::provides(string const & p) const
1089 {
1090         return provides_.find(p) != provides_.end();
1091 }
1092
1093
1094 bool DocumentClass::hasTocLevels() const
1095 {
1096         return min_toclevel_ != Layout::NOT_IN_TOC;
1097 }
1098
1099
1100 ostream & operator<<(ostream & os, PageSides p)
1101 {
1102         switch (p) {
1103         case OneSide:
1104                 os << '1';
1105                 break;
1106         case TwoSides:
1107                 os << '2';
1108                 break;
1109         }
1110         return os;
1111 }
1112
1113
1114 } // namespace lyx