]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
Fix the rest of bug 5010.
[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
64 int const FORMAT = 7;
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::emptylayout_ = from_ascii("Plain Layout");
115
116
117 InsetLayout DocumentClass::empty_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)
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 };
187
188
189 namespace {
190
191         LexerKeyword textClassTags[] = {
192                 { "addtopreamble",   TC_ADDTOPREAMBLE },
193                 { "classoptions",    TC_CLASSOPTIONS },
194                 { "columns",         TC_COLUMNS },
195                 { "counter",         TC_COUNTER },
196                 { "defaultfont",     TC_DEFAULTFONT },
197                 { "defaultstyle",    TC_DEFAULTSTYLE },
198                 { "float",           TC_FLOAT },
199                 { "format",          TC_FORMAT },
200                 { "input",           TC_INPUT },
201                 { "insetlayout",     TC_INSETLAYOUT },
202                 { "leftmargin",      TC_LEFTMARGIN },
203                 { "nofloat",         TC_NOFLOAT },
204                 { "nostyle",         TC_NOSTYLE },
205                 { "outputtype",      TC_OUTPUTTYPE },
206                 { "pagestyle",       TC_PAGESTYLE },
207                 { "preamble",        TC_PREAMBLE },
208                 { "provides",        TC_PROVIDES },
209                 { "requires",        TC_REQUIRES },
210                 { "rightmargin",     TC_RIGHTMARGIN },
211                 { "secnumdepth",     TC_SECNUMDEPTH },
212                 { "sides",           TC_SIDES },
213                 { "style",           TC_STYLE },
214                 { "titlelatexname",  TC_TITLELATEXNAME },
215                 { "titlelatextype",  TC_TITLELATEXTYPE },
216                 { "tocdepth",        TC_TOCDEPTH }
217         };
218         
219 } //namespace anon
220
221
222 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
223 {
224         LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
225                 FileName const tempfile = FileName::tempName();
226                 bool success = layout2layout(filename, tempfile);
227                 if (success)
228                         success = read(tempfile, rt);
229                 tempfile.removeFile();
230                 return success;
231 }
232
233 bool TextClass::read(FileName const & filename, ReadType rt)
234 {
235         if (!filename.isReadableFile()) {
236                 lyxerr << "Cannot read layout file `" << filename << "'."
237                        << endl;
238                 return false;
239         }
240
241         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
242                 to_utf8(makeDisplayPath(filename.absFilename())));
243
244         // Define the `empty' layout used in table cells, ert, etc. Note that 
245         // we do this before loading any layout file, so that classes can 
246         // override features of this layout if they should choose to do so.
247         if (rt == BASECLASS && !hasLayout(emptylayout_)) {
248                 static char const * s = "Margin Static\n"
249                         "LatexType Paragraph\n"
250                         "LatexName dummy\n"
251                         "Align Block\n"
252                         "AlignPossible Left, Right, Center\n"
253                         "LabelType No_Label\n"
254                         "End";
255                 istringstream ss(s);
256                 Lexer lex(textClassTags);
257                 lex.setStream(ss);
258                 Layout lay;
259                 lay.setName(emptylayout_);
260                 if (!readStyle(lex, lay)) {
261                         // The only way this happens is because the hardcoded layout above
262                         // is wrong.
263                         LASSERT(false, /**/);
264                 };
265                 layoutlist_.push_back(lay);
266         }
267
268         Lexer lexrc(textClassTags);
269         lexrc.setFile(filename);
270         ReturnValues retval = read(lexrc, rt);
271         
272         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
273                         to_utf8(makeDisplayPath(filename.absFilename())));
274         
275         if (retval != FORMAT_MISMATCH) 
276                 return retval == OK;
277         
278         bool const worx = convertLayoutFormat(filename, rt);
279         if (!worx) {
280                 lyxerr << "Unable to convert " << filename << 
281                         " to format " << FORMAT << std::endl;
282                 return false;
283         }
284         return true;
285 }
286
287
288 bool TextClass::validate(std::string const & str)
289 {
290         TextClass tc;
291         return tc.read(str, VALIDATION);
292 }
293
294
295 bool TextClass::read(std::string const & str, ReadType rt) 
296 {
297         Lexer lexrc(textClassTags);
298         istringstream is(str);
299         lexrc.setStream(is);
300         ReturnValues retval = read(lexrc, rt);
301
302         if (retval != FORMAT_MISMATCH) 
303                 return retval == OK;
304
305         // write the layout string to a temporary file
306         FileName const tempfile = FileName::tempName();
307         ofstream os(tempfile.toFilesystemEncoding().c_str());
308         if (!os) {
309                 LYXERR0("Unable to create tempoary file");
310                 return false;
311         }
312         os << str;
313         os.close();
314
315         // now try to convert it
316         bool const worx = convertLayoutFormat(tempfile, rt);
317         if (!worx) {
318                 LYXERR0("Unable to convert internal layout information to format " 
319                         << FORMAT);
320         }
321         tempfile.removeFile();
322         return worx;
323 }
324
325
326 // Reads a textclass structure from file.
327 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt) 
328 {
329         bool error = !lexrc.isOK();
330
331         // Format of files before the 'Format' tag was introduced
332         int format = 1;
333
334         // parsing
335         while (lexrc.isOK() && !error) {
336                 int le = lexrc.lex();
337
338                 switch (le) {
339                 case Lexer::LEX_FEOF:
340                         continue;
341
342                 case Lexer::LEX_UNDEF:
343                         lexrc.printError("Unknown TextClass tag `$$Token'");
344                         error = true;
345                         continue;
346
347                 default:
348                         break;
349                 }
350
351                 switch (static_cast<TextClassTags>(le)) {
352
353                 case TC_FORMAT:
354                         if (lexrc.next())
355                                 format = lexrc.getInteger();
356                         break;
357
358                 case TC_OUTPUTTYPE:   // output type definition
359                         readOutputType(lexrc);
360                         break;
361
362                 case TC_INPUT: // Include file
363                         if (lexrc.next()) {
364                                 string const inc = lexrc.getString();
365                                 FileName tmp = libFileSearch("layouts", inc,
366                                                             "layout");
367
368                                 if (tmp.empty()) {
369                                         lexrc.printError("Could not find input file: " + inc);
370                                         error = true;
371                                 } else if (!read(tmp, MERGE)) {
372                                         lexrc.printError("Error reading input"
373                                                          "file: " + tmp.absFilename());
374                                         error = true;
375                                 }
376                         }
377                         break;
378
379                 case TC_DEFAULTSTYLE:
380                         if (lexrc.next()) {
381                                 docstring const name = from_utf8(subst(lexrc.getString(),
382                                                           '_', ' '));
383                                 defaultlayout_ = name;
384                         }
385                         break;
386
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 layout;
404                                         layout.setName(name);
405                                         error = !readStyle(lexrc, layout);
406                                         if (!error)
407                                                 layoutlist_.push_back(layout);
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 layout;
419                                 //readStyle(lexrc, layout);
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                                 // else there was an error, so forget it
528                         }
529                         break;
530
531                 case TC_FLOAT:
532                         readFloat(lexrc);
533                         break;
534
535                 case TC_COUNTER:
536                         readCounter(lexrc);
537                         break;
538
539                 case TC_TITLELATEXTYPE:
540                         readTitleType(lexrc);
541                         break;
542
543                 case TC_TITLELATEXNAME:
544                         if (lexrc.next())
545                                 titlename_ = lexrc.getString();
546                         break;
547
548                 case TC_NOFLOAT:
549                         if (lexrc.next()) {
550                                 string const nofloat = lexrc.getString();
551                                 floatlist_.erase(nofloat);
552                         }
553                         break;
554                 }
555
556                 //Note that this is triggered the first time through the loop unless
557                 //we hit a format tag.
558                 if (format != FORMAT)
559                         break;
560         }
561
562         if (format != FORMAT)
563                 return FORMAT_MISMATCH;
564
565         if (rt != BASECLASS) 
566                 return (error ? ERROR : OK);
567
568         if (defaultlayout_.empty()) {
569                 LYXERR0("Error: Textclass '" << name_
570                                                 << "' is missing a defaultstyle.");
571                 error = true;
572         }
573                 
574         // Try to erase "stdinsets" from the provides_ set. 
575         // The
576         //   Provides stdinsets 1
577         // declaration simply tells us that the standard insets have been
578         // defined. (It's found in stdinsets.inc but could also be used in
579         // user-defined files.) There isn't really any such package. So we
580         // might as well go ahead and erase it.
581         // If we do not succeed, then it was not there, which means that
582         // the textclass did not provide the definitions of the standard
583         // insets. So we need to try to load them.
584         int erased = provides_.erase("stdinsets");
585         if (!erased) {
586                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
587
588                 if (tmp.empty()) {
589                         throw ExceptionMessage(WarningException, _("Missing File"),
590                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
591                         error = true;
592                 } else if (!read(tmp, MERGE)) {
593                         throw ExceptionMessage(WarningException, _("Corrupt File"),
594                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
595                         error = true;
596                 }
597         }
598
599         min_toclevel_ = Layout::NOT_IN_TOC;
600         max_toclevel_ = Layout::NOT_IN_TOC;
601         const_iterator lit = begin();
602         const_iterator len = end();
603         for (; lit != len; ++lit) {
604                 int const toclevel = lit->toclevel;
605                 if (toclevel != Layout::NOT_IN_TOC) {
606                         if (min_toclevel_ == Layout::NOT_IN_TOC)
607                                 min_toclevel_ = toclevel;
608                         else
609                                 min_toclevel_ = min(min_toclevel_, toclevel);
610                         max_toclevel_ = max(max_toclevel_, toclevel);
611                 }
612         }
613         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
614                 << ", maximum is " << max_toclevel_);
615
616         return (error ? ERROR : OK);
617 }
618
619
620 void TextClass::readTitleType(Lexer & lexrc)
621 {
622         LexerKeyword titleTypeTags[] = {
623                 { "commandafter", TITLE_COMMAND_AFTER },
624                 { "environment",  TITLE_ENVIRONMENT }
625         };
626
627         PushPopHelper pph(lexrc, titleTypeTags);
628
629         int le = lexrc.lex();
630         switch (le) {
631         case Lexer::LEX_UNDEF:
632                 lexrc.printError("Unknown output type `$$Token'");
633                 break;
634         case TITLE_COMMAND_AFTER:
635         case TITLE_ENVIRONMENT:
636                 titletype_ = static_cast<TitleLatexType>(le);
637                 break;
638         default:
639                 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
640                 break;
641         }
642 }
643
644
645 void TextClass::readOutputType(Lexer & lexrc)
646 {
647         LexerKeyword outputTypeTags[] = {
648                 { "docbook",  DOCBOOK },
649                 { "latex",    LATEX },
650                 { "literate", LITERATE }
651         };
652
653         PushPopHelper pph(lexrc, outputTypeTags);
654
655         int le = lexrc.lex();
656         switch (le) {
657         case Lexer::LEX_UNDEF:
658                 lexrc.printError("Unknown output type `$$Token'");
659                 return;
660         case LATEX:
661         case DOCBOOK:
662         case LITERATE:
663                 outputType_ = static_cast<OutputType>(le);
664                 break;
665         default:
666                 LYXERR0("Unhandled value " << le);
667                 break;
668         }
669 }
670
671
672 void TextClass::readClassOptions(Lexer & lexrc)
673 {
674         enum {
675                 CO_FONTSIZE = 1,
676                 CO_PAGESTYLE,
677                 CO_OTHER,
678                 CO_HEADER,
679                 CO_END
680         };
681
682         LexerKeyword classOptionsTags[] = {
683                 {"end",       CO_END },
684                 {"fontsize",  CO_FONTSIZE },
685                 {"header",    CO_HEADER },
686                 {"other",     CO_OTHER },
687                 {"pagestyle", CO_PAGESTYLE }
688         };
689
690         lexrc.pushTable(classOptionsTags);
691         bool getout = false;
692         while (!getout && lexrc.isOK()) {
693                 int le = lexrc.lex();
694                 switch (le) {
695                 case Lexer::LEX_UNDEF:
696                         lexrc.printError("Unknown ClassOption tag `$$Token'");
697                         continue;
698                 default: break;
699                 }
700                 switch (le) {
701                 case CO_FONTSIZE:
702                         lexrc.next();
703                         opt_fontsize_ = rtrim(lexrc.getString());
704                         break;
705                 case CO_PAGESTYLE:
706                         lexrc.next();
707                         opt_pagestyle_ = rtrim(lexrc.getString());
708                         break;
709                 case CO_OTHER:
710                         lexrc.next();
711                         options_ = lexrc.getString();
712                         break;
713                 case CO_HEADER:
714                         lexrc.next();
715                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
716                         break;
717                 case CO_END:
718                         getout = true;
719                         break;
720                 }
721         }
722         lexrc.popTable();
723 }
724
725
726 void TextClass::readFloat(Lexer & lexrc)
727 {
728         enum {
729                 FT_TYPE = 1,
730                 FT_NAME,
731                 FT_PLACEMENT,
732                 FT_EXT,
733                 FT_WITHIN,
734                 FT_STYLE,
735                 FT_LISTNAME,
736                 FT_BUILTIN,
737                 FT_END
738         };
739
740         LexerKeyword floatTags[] = {
741                 { "end", FT_END },
742                 { "extension", FT_EXT },
743                 { "guiname", FT_NAME },
744                 { "latexbuiltin", FT_BUILTIN },
745                 { "listname", FT_LISTNAME },
746                 { "numberwithin", FT_WITHIN },
747                 { "placement", FT_PLACEMENT },
748                 { "style", FT_STYLE },
749                 { "type", FT_TYPE }
750         };
751
752         lexrc.pushTable(floatTags);
753
754         string type;
755         string placement;
756         string ext;
757         string within;
758         string style;
759         string name;
760         string listName;
761         bool builtin = false;
762
763         bool getout = false;
764         while (!getout && lexrc.isOK()) {
765                 int le = lexrc.lex();
766                 switch (le) {
767                 case Lexer::LEX_UNDEF:
768                         lexrc.printError("Unknown float tag `$$Token'");
769                         continue;
770                 default: break;
771                 }
772                 switch (le) {
773                 case FT_TYPE:
774                         lexrc.next();
775                         type = lexrc.getString();
776                         if (floatlist_.typeExist(type)) {
777                                 Floating const & fl = floatlist_.getType(type);
778                                 placement = fl.placement();
779                                 ext = fl.ext();
780                                 within = fl.within();
781                                 style = fl.style();
782                                 name = fl.name();
783                                 listName = fl.listName();
784                                 builtin = fl.builtin();
785                         } 
786                         break;
787                 case FT_NAME:
788                         lexrc.next();
789                         name = lexrc.getString();
790                         break;
791                 case FT_PLACEMENT:
792                         lexrc.next();
793                         placement = lexrc.getString();
794                         break;
795                 case FT_EXT:
796                         lexrc.next();
797                         ext = lexrc.getString();
798                         break;
799                 case FT_WITHIN:
800                         lexrc.next();
801                         within = lexrc.getString();
802                         if (within == "none")
803                                 within.erase();
804                         break;
805                 case FT_STYLE:
806                         lexrc.next();
807                         style = lexrc.getString();
808                         break;
809                 case FT_LISTNAME:
810                         lexrc.next();
811                         listName = lexrc.getString();
812                         break;
813                 case FT_BUILTIN:
814                         lexrc.next();
815                         builtin = lexrc.getBool();
816                         break;
817                 case FT_END:
818                         getout = true;
819                         break;
820                 }
821         }
822
823         // Here if have a full float if getout == true
824         if (getout) {
825                 Floating fl(type, placement, ext, within,
826                             style, name, listName, builtin);
827                 floatlist_.newFloat(fl);
828                 // each float has its own counter
829                 counters_.newCounter(from_ascii(type), from_ascii(within),
830                                       docstring(), docstring());
831                 // also define sub-float counters
832                 docstring const subtype = "sub-" + from_ascii(type);
833                 counters_.newCounter(subtype, from_ascii(type),
834                                       "\\alph{" + subtype + "}", docstring());
835         }
836
837         lexrc.popTable();
838 }
839
840
841 void TextClass::readCounter(Lexer & lexrc)
842 {
843         enum {
844                 CT_NAME = 1,
845                 CT_WITHIN,
846                 CT_LABELSTRING,
847                 CT_LABELSTRING_APPENDIX,
848                 CT_END
849         };
850
851         LexerKeyword counterTags[] = {
852                 { "end", CT_END },
853                 { "labelstring", CT_LABELSTRING },
854                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
855                 { "name", CT_NAME },
856                 { "within", CT_WITHIN }
857         };
858
859         lexrc.pushTable(counterTags);
860
861         docstring name;
862         docstring within;
863         docstring labelstring;
864         docstring labelstring_appendix;
865
866         bool getout = false;
867         while (!getout && lexrc.isOK()) {
868                 int le = lexrc.lex();
869                 switch (le) {
870                 case Lexer::LEX_UNDEF:
871                         lexrc.printError("Unknown counter tag `$$Token'");
872                         continue;
873                 default: break;
874                 }
875                 switch (le) {
876                 case CT_NAME:
877                         lexrc.next();
878                         name = lexrc.getDocString();
879                         if (counters_.hasCounter(name))
880                                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
881                         else
882                                 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
883                         break;
884                 case CT_WITHIN:
885                         lexrc.next();
886                         within = lexrc.getDocString();
887                         if (within == "none")
888                                 within.erase();
889                         break;
890                 case CT_LABELSTRING:
891                         lexrc.next();
892                         labelstring = lexrc.getDocString();
893                         labelstring_appendix = labelstring;
894                         break;
895                 case CT_LABELSTRING_APPENDIX:
896                         lexrc.next();
897                         labelstring_appendix = lexrc.getDocString();
898                         break;
899                 case CT_END:
900                         getout = true;
901                         break;
902                 }
903         }
904
905         // Here if have a full counter if getout == true
906         if (getout)
907                 counters_.newCounter(name, within, 
908                                       labelstring, labelstring_appendix);
909
910         lexrc.popTable();
911 }
912
913
914 bool TextClass::hasLayout(docstring const & n) const
915 {
916         docstring const name = n.empty() ? defaultLayoutName() : n;
917
918         return find_if(layoutlist_.begin(), layoutlist_.end(),
919                        LayoutNamesEqual(name))
920                 != layoutlist_.end();
921 }
922
923
924
925 Layout const & TextClass::operator[](docstring const & name) const
926 {
927         LASSERT(!name.empty(), /**/);
928
929         const_iterator it = 
930                 find_if(begin(), end(), LayoutNamesEqual(name));
931
932         if (it == end()) {
933                 lyxerr << "We failed to find the layout '" << to_utf8(name)
934                        << "' in the layout list. You MUST investigate!"
935                        << endl;
936                 for (const_iterator cit = begin(); cit != end(); ++cit)
937                         lyxerr  << " " << to_utf8(cit->name()) << endl;
938
939                 // we require the name to exist
940                 LASSERT(false, /**/);
941         }
942
943         return *it;
944 }
945
946
947 Layout & TextClass::operator[](docstring const & name)
948 {
949         LASSERT(!name.empty(), /**/);
950
951         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
952
953         if (it == end()) {
954                 LYXERR0("We failed to find the layout '" << to_utf8(name)
955                        << "' in the layout list. You MUST investigate!");
956                 for (const_iterator cit = begin(); cit != end(); ++cit)
957                         LYXERR0(" " << to_utf8(cit->name()));
958
959                 // we require the name to exist
960                 LASSERT(false, /**/);
961         }
962
963         return *it;
964 }
965
966
967 bool TextClass::deleteLayout(docstring const & name)
968 {
969         if (name == defaultLayoutName() || name == emptyLayoutName())
970                 return false;
971
972         LayoutList::iterator it =
973                 remove_if(layoutlist_.begin(), layoutlist_.end(),
974                           LayoutNamesEqual(name));
975
976         LayoutList::iterator end = layoutlist_.end();
977         bool const ret = (it != end);
978         layoutlist_.erase(it, end);
979         return ret;
980 }
981
982
983 // Load textclass info if not loaded yet
984 bool TextClass::load(string const & path) const
985 {
986         if (loaded_)
987                 return true;
988
989         // Read style-file, provided path is searched before the system ones
990         FileName layout_file;
991         if (!path.empty())
992                 layout_file = FileName(addName(path, name_ + ".layout"));
993         if (layout_file.empty() || !layout_file.exists())
994                 layout_file = libFileSearch("layouts", name_, "layout");
995         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
996
997         if (!loaded_) {
998                 lyxerr << "Error reading `"
999                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
1000                        << "'\n(Check `" << name_
1001                        << "')\nCheck your installation and "
1002                         "try Options/Reconfigure..." << endl;
1003         }
1004
1005         return loaded_;
1006 }
1007
1008
1009 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
1010 {
1011         docstring n = name;
1012         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1013         while (!n.empty()) {
1014                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1015                 if (cit != cen && cit->first == n)
1016                         return cit->second;
1017                 size_t i = n.find(':');
1018                 if (i == string::npos)
1019                         break;
1020                 n = n.substr(0,i);
1021         }
1022         return empty_insetlayout_;
1023 }
1024
1025
1026 docstring const & TextClass::defaultLayoutName() const
1027 {
1028         // This really should come from the actual layout... (Lgb)
1029         return defaultlayout_;
1030 }
1031
1032
1033 Layout const & TextClass::defaultLayout() const
1034 {
1035         return operator[](defaultLayoutName());
1036 }
1037
1038
1039 bool TextClass::isDefaultLayout(Layout const & layout) const 
1040 {
1041         return layout.name() == defaultLayoutName();
1042 }
1043
1044
1045 bool TextClass::isEmptyLayout(Layout const & layout) const 
1046 {
1047         return layout.name() == emptyLayoutName();
1048 }
1049
1050
1051 /////////////////////////////////////////////////////////////////////////
1052 //
1053 // DocumentClassBundle
1054 //
1055 /////////////////////////////////////////////////////////////////////////
1056
1057 DocumentClassBundle::~DocumentClassBundle()
1058 {
1059         for (size_t i = 0; i != documentClasses_.size(); ++i)
1060                 delete documentClasses_[i];
1061         documentClasses_.clear();
1062 }
1063
1064 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1065 {
1066         DocumentClass * dc = new DocumentClass(baseClass);
1067         documentClasses_.push_back(dc);
1068         return *documentClasses_.back();
1069 }
1070
1071
1072 DocumentClassBundle & DocumentClassBundle::get()
1073 {
1074         static DocumentClassBundle singleton; 
1075         return singleton; 
1076 }
1077
1078
1079 /////////////////////////////////////////////////////////////////////////
1080 //
1081 // DocumentClass
1082 //
1083 /////////////////////////////////////////////////////////////////////////
1084
1085 DocumentClass::DocumentClass(LayoutFile const & tc)
1086         : TextClass(tc)
1087 {}
1088
1089
1090 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1091 {
1092         LayoutList::const_iterator it  = layoutlist_.begin();
1093         LayoutList::const_iterator end = layoutlist_.end();
1094         for (; it != end; ++it)
1095                 if (it->latexname() == lay)
1096                         return true;
1097         return false;
1098 }
1099
1100
1101 bool DocumentClass::provides(string const & p) const
1102 {
1103         return provides_.find(p) != provides_.end();
1104 }
1105
1106
1107 bool DocumentClass::hasTocLevels() const
1108 {
1109         return min_toclevel_ != Layout::NOT_IN_TOC;
1110 }
1111
1112
1113 /////////////////////////////////////////////////////////////////////////
1114 //
1115 // PageSides
1116 //
1117 /////////////////////////////////////////////////////////////////////////
1118
1119 ostream & operator<<(ostream & os, PageSides p)
1120 {
1121         switch (p) {
1122         case OneSide:
1123                 os << '1';
1124                 break;
1125         case TwoSides:
1126                 os << '2';
1127                 break;
1128         }
1129         return os;
1130 }
1131
1132
1133 } // namespace lyx