]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
b3ac4898513fe72ffcfd1455e8147e1e1733fe6a
[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_ENVIRONMENT,
167         TC_NOSTYLE,
168         TC_COLUMNS,
169         TC_SIDES,
170         TC_PAGESTYLE,
171         TC_DEFAULTFONT,
172         TC_SECNUMDEPTH,
173         TC_TOCDEPTH,
174         TC_CLASSOPTIONS,
175         TC_PREAMBLE,
176         TC_PROVIDES,
177         TC_REQUIRES,
178         TC_LEFTMARGIN,
179         TC_RIGHTMARGIN,
180         TC_FLOAT,
181         TC_COUNTER,
182         TC_NOFLOAT,
183         TC_TITLELATEXNAME,
184         TC_TITLELATEXTYPE,
185         TC_FORMAT,
186         TC_ADDTOPREAMBLE
187 };
188
189
190 namespace {
191
192         LexerKeyword textClassTags[] = {
193                 { "addtopreamble",   TC_ADDTOPREAMBLE },
194                 { "classoptions",    TC_CLASSOPTIONS },
195                 { "columns",         TC_COLUMNS },
196                 { "counter",         TC_COUNTER },
197                 { "defaultfont",     TC_DEFAULTFONT },
198                 { "defaultstyle",    TC_DEFAULTSTYLE },
199                 { "environment",     TC_ENVIRONMENT },
200                 { "float",           TC_FLOAT },
201                 { "format",          TC_FORMAT },
202                 { "input",           TC_INPUT },
203                 { "insetlayout",     TC_INSETLAYOUT },
204                 { "leftmargin",      TC_LEFTMARGIN },
205                 { "nofloat",         TC_NOFLOAT },
206                 { "nostyle",         TC_NOSTYLE },
207                 { "outputtype",      TC_OUTPUTTYPE },
208                 { "pagestyle",       TC_PAGESTYLE },
209                 { "preamble",        TC_PREAMBLE },
210                 { "provides",        TC_PROVIDES },
211                 { "requires",        TC_REQUIRES },
212                 { "rightmargin",     TC_RIGHTMARGIN },
213                 { "secnumdepth",     TC_SECNUMDEPTH },
214                 { "sides",           TC_SIDES },
215                 { "style",           TC_STYLE },
216                 { "titlelatexname",  TC_TITLELATEXNAME },
217                 { "titlelatextype",  TC_TITLELATEXTYPE },
218                 { "tocdepth",        TC_TOCDEPTH }
219         };
220         
221 } //namespace anon
222
223
224 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
225 {
226         LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
227                 FileName const tempfile = FileName::tempName();
228                 bool success = layout2layout(filename, tempfile);
229                 if (success)
230                         success = read(tempfile, rt);
231                 tempfile.removeFile();
232                 return success;
233 }
234
235 bool TextClass::read(FileName const & filename, ReadType rt)
236 {
237         if (!filename.isReadableFile()) {
238                 lyxerr << "Cannot read layout file `" << filename << "'."
239                        << endl;
240                 return false;
241         }
242
243         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
244                 to_utf8(makeDisplayPath(filename.absFilename())));
245
246         // Define the `empty' layout used in table cells, ert, etc. Note that 
247         // we do this before loading any layout file, so that classes can 
248         // override features of this layout if they should choose to do so.
249         if (rt == BASECLASS && !hasLayout(emptylayout_)) {
250                 static char const * s = "Margin Static\n"
251                         "LatexType Paragraph\n"
252                         "LatexName dummy\n"
253                         "Align Block\n"
254                         "AlignPossible Left, Right, Center\n"
255                         "LabelType No_Label\n"
256                         "End";
257                 istringstream ss(s);
258                 Lexer lex(textClassTags);
259                 lex.setStream(ss);
260                 Layout lay;
261                 lay.setName(emptylayout_);
262                 if (!readStyle(lex, lay)) {
263                         // The only way this happens is because the hardcoded layout above
264                         // is wrong.
265                         LASSERT(false, /**/);
266                 };
267                 layoutlist_.push_back(lay);
268         }
269
270         Lexer lexrc(textClassTags);
271         lexrc.setFile(filename);
272         ReturnValues retval = read(lexrc, rt);
273         
274         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
275                         to_utf8(makeDisplayPath(filename.absFilename())));
276         
277         if (retval != FORMAT_MISMATCH) 
278                 return retval == OK;
279         
280         bool const worx = convertLayoutFormat(filename, rt);
281         if (!worx) {
282                 lyxerr << "Unable to convert " << filename << 
283                         " to format " << FORMAT << std::endl;
284                 return false;
285         }
286         return true;
287 }
288
289
290 bool TextClass::validate(std::string const & str)
291 {
292         TextClass tc;
293         return tc.read(str, VALIDATION);
294 }
295
296
297 bool TextClass::read(std::string const & str, ReadType rt) 
298 {
299         Lexer lexrc(textClassTags);
300         istringstream is(str);
301         lexrc.setStream(is);
302         ReturnValues retval = read(lexrc, rt);
303
304         if (retval != FORMAT_MISMATCH) 
305                 return retval == OK;
306
307         // write the layout string to a temporary file
308         FileName const tempfile = FileName::tempName();
309         ofstream os(tempfile.toFilesystemEncoding().c_str());
310         if (!os) {
311                 LYXERR0("Unable to create tempoary file");
312                 return false;
313         }
314         os << str;
315         os.close();
316
317         // now try to convert it
318         bool const worx = convertLayoutFormat(tempfile, rt);
319         if (!worx) {
320                 LYXERR0("Unable to convert internal layout information to format " 
321                         << FORMAT);
322         }
323         tempfile.removeFile();
324         return worx;
325 }
326
327
328 // Reads a textclass structure from file.
329 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt) 
330 {
331         bool error = !lexrc.isOK();
332
333         // Format of files before the 'Format' tag was introduced
334         int format = 1;
335
336         // parsing
337         while (lexrc.isOK() && !error) {
338                 int le = lexrc.lex();
339
340                 switch (le) {
341                 case Lexer::LEX_FEOF:
342                         continue;
343
344                 case Lexer::LEX_UNDEF:
345                         lexrc.printError("Unknown TextClass tag `$$Token'");
346                         error = true;
347                         continue;
348
349                 default:
350                         break;
351                 }
352
353                 switch (static_cast<TextClassTags>(le)) {
354
355                 case TC_FORMAT:
356                         if (lexrc.next())
357                                 format = lexrc.getInteger();
358                         break;
359
360                 case TC_OUTPUTTYPE:   // output type definition
361                         readOutputType(lexrc);
362                         break;
363
364                 case TC_INPUT: // Include file
365                         if (lexrc.next()) {
366                                 string const inc = lexrc.getString();
367                                 FileName tmp = libFileSearch("layouts", inc,
368                                                             "layout");
369
370                                 if (tmp.empty()) {
371                                         lexrc.printError("Could not find input file: " + inc);
372                                         error = true;
373                                 } else if (!read(tmp, MERGE)) {
374                                         lexrc.printError("Error reading input"
375                                                          "file: " + tmp.absFilename());
376                                         error = true;
377                                 }
378                         }
379                         break;
380
381                 case TC_DEFAULTSTYLE:
382                         if (lexrc.next()) {
383                                 docstring const name = from_utf8(subst(lexrc.getString(),
384                                                           '_', ' '));
385                                 defaultlayout_ = name;
386                         }
387                         break;
388
389                 case TC_ENVIRONMENT:
390                 case TC_STYLE:
391                         if (lexrc.next()) {
392                                 docstring const name = from_utf8(subst(lexrc.getString(),
393                                                     '_', ' '));
394                                 if (name.empty()) {
395                                         string s = "Could not read name for style: `$$Token' "
396                                                 + lexrc.getString() + " is probably not valid UTF-8!";
397                                         lexrc.printError(s.c_str());
398                                         Layout lay;
399                                         // Since we couldn't read the name, we just scan the rest
400                                         // of the style and discard it.
401                                         error = !readStyle(lexrc, lay);
402                                 } else if (hasLayout(name)) {
403                                         Layout & lay = operator[](name);
404                                         error = !readStyle(lexrc, lay);
405                                 } else {
406                                         Layout layout;
407                                         layout.setName(name);
408                                         if (le == TC_ENVIRONMENT)
409                                                 layout.is_environment = true;
410                                         error = !readStyle(lexrc, layout);
411                                         if (!error)
412                                                 layoutlist_.push_back(layout);
413
414                                         if (defaultlayout_.empty()) {
415                                                 // We do not have a default layout yet, so we choose
416                                                 // the first layout we encounter.
417                                                 defaultlayout_ = name;
418                                         }
419                                 }
420                         }
421                         else {
422                                 //FIXME Should we also eat the style here? viz:
423                                 //Layout layout;
424                                 //readStyle(lexrc, layout);
425                                 //as above...
426                                 lexrc.printError("No name given for style: `$$Token'.");
427                                 error = true;
428                         }
429                         break;
430
431                 case TC_NOSTYLE:
432                         if (lexrc.next()) {
433                                 docstring const style = from_utf8(subst(lexrc.getString(),
434                                                      '_', ' '));
435                                 if (!deleteLayout(style))
436                                         lyxerr << "Cannot delete style `"
437                                                << to_utf8(style) << '\'' << endl;
438                         }
439                         break;
440
441                 case TC_COLUMNS:
442                         if (lexrc.next())
443                                 columns_ = lexrc.getInteger();
444                         break;
445
446                 case TC_SIDES:
447                         if (lexrc.next()) {
448                                 switch (lexrc.getInteger()) {
449                                 case 1: sides_ = OneSide; break;
450                                 case 2: sides_ = TwoSides; break;
451                                 default:
452                                         lyxerr << "Impossible number of page"
453                                                 " sides, setting to one."
454                                                << endl;
455                                         sides_ = OneSide;
456                                         break;
457                                 }
458                         }
459                         break;
460
461                 case TC_PAGESTYLE:
462                         lexrc.next();
463                         pagestyle_ = rtrim(lexrc.getString());
464                         break;
465
466                 case TC_DEFAULTFONT:
467                         defaultfont_ = lyxRead(lexrc);
468                         if (!defaultfont_.resolved()) {
469                                 lexrc.printError("Warning: defaultfont should "
470                                                  "be fully instantiated!");
471                                 defaultfont_.realize(sane_font);
472                         }
473                         break;
474
475                 case TC_SECNUMDEPTH:
476                         lexrc.next();
477                         secnumdepth_ = lexrc.getInteger();
478                         break;
479
480                 case TC_TOCDEPTH:
481                         lexrc.next();
482                         tocdepth_ = lexrc.getInteger();
483                         break;
484
485                 // First step to support options
486                 case TC_CLASSOPTIONS:
487                         readClassOptions(lexrc);
488                         break;
489
490                 case TC_PREAMBLE:
491                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
492                         break;
493
494                 case TC_ADDTOPREAMBLE:
495                         preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
496                         break;
497
498                 case TC_PROVIDES: {
499                         lexrc.next();
500                         string const feature = lexrc.getString();
501                         lexrc.next();
502                         if (lexrc.getInteger())
503                                 provides_.insert(feature);
504                         else
505                                 provides_.erase(feature);
506                         break;
507                 }
508
509                 case TC_REQUIRES: {
510                         lexrc.eatLine();
511                         vector<string> const req 
512                                 = getVectorFromString(lexrc.getString());
513                         requires_.insert(req.begin(), req.end());
514                         break;
515                 }
516
517                 case TC_LEFTMARGIN:     // left margin type
518                         if (lexrc.next())
519                                 leftmargin_ = lexrc.getDocString();
520                         break;
521
522                 case TC_RIGHTMARGIN:    // right margin type
523                         if (lexrc.next())
524                                 rightmargin_ = lexrc.getDocString();
525                         break;
526
527                 case TC_INSETLAYOUT:
528                         if (lexrc.next()) {
529                                 InsetLayout il;
530                                 if (il.read(lexrc))
531                                         insetlayoutlist_[il.name()] = il;
532                                 // else there was an error, so forget it
533                         }
534                         break;
535
536                 case TC_FLOAT:
537                         readFloat(lexrc);
538                         break;
539
540                 case TC_COUNTER:
541                         readCounter(lexrc);
542                         break;
543
544                 case TC_TITLELATEXTYPE:
545                         readTitleType(lexrc);
546                         break;
547
548                 case TC_TITLELATEXNAME:
549                         if (lexrc.next())
550                                 titlename_ = lexrc.getString();
551                         break;
552
553                 case TC_NOFLOAT:
554                         if (lexrc.next()) {
555                                 string const nofloat = lexrc.getString();
556                                 floatlist_.erase(nofloat);
557                         }
558                         break;
559                 }
560
561                 //Note that this is triggered the first time through the loop unless
562                 //we hit a format tag.
563                 if (format != FORMAT)
564                         break;
565         }
566
567         if (format != FORMAT)
568                 return FORMAT_MISMATCH;
569
570         if (rt != BASECLASS) 
571                 return (error ? ERROR : OK);
572
573         if (defaultlayout_.empty()) {
574                 LYXERR0("Error: Textclass '" << name_
575                                                 << "' is missing a defaultstyle.");
576                 error = true;
577         }
578                 
579         // Try to erase "stdinsets" from the provides_ set. 
580         // The
581         //   Provides stdinsets 1
582         // declaration simply tells us that the standard insets have been
583         // defined. (It's found in stdinsets.inc but could also be used in
584         // user-defined files.) There isn't really any such package. So we
585         // might as well go ahead and erase it.
586         // If we do not succeed, then it was not there, which means that
587         // the textclass did not provide the definitions of the standard
588         // insets. So we need to try to load them.
589         int erased = provides_.erase("stdinsets");
590         if (!erased) {
591                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
592
593                 if (tmp.empty()) {
594                         throw ExceptionMessage(WarningException, _("Missing File"),
595                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
596                         error = true;
597                 } else if (!read(tmp, MERGE)) {
598                         throw ExceptionMessage(WarningException, _("Corrupt File"),
599                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
600                         error = true;
601                 }
602         }
603
604         min_toclevel_ = Layout::NOT_IN_TOC;
605         max_toclevel_ = Layout::NOT_IN_TOC;
606         const_iterator lit = begin();
607         const_iterator len = end();
608         for (; lit != len; ++lit) {
609                 int const toclevel = lit->toclevel;
610                 if (toclevel != Layout::NOT_IN_TOC) {
611                         if (min_toclevel_ == Layout::NOT_IN_TOC)
612                                 min_toclevel_ = toclevel;
613                         else
614                                 min_toclevel_ = min(min_toclevel_, toclevel);
615                         max_toclevel_ = max(max_toclevel_, toclevel);
616                 }
617         }
618         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
619                 << ", maximum is " << max_toclevel_);
620
621         return (error ? ERROR : OK);
622 }
623
624
625 void TextClass::readTitleType(Lexer & lexrc)
626 {
627         LexerKeyword titleTypeTags[] = {
628                 { "commandafter", TITLE_COMMAND_AFTER },
629                 { "environment",  TITLE_ENVIRONMENT }
630         };
631
632         PushPopHelper pph(lexrc, titleTypeTags);
633
634         int le = lexrc.lex();
635         switch (le) {
636         case Lexer::LEX_UNDEF:
637                 lexrc.printError("Unknown output type `$$Token'");
638                 break;
639         case TITLE_COMMAND_AFTER:
640         case TITLE_ENVIRONMENT:
641                 titletype_ = static_cast<TitleLatexType>(le);
642                 break;
643         default:
644                 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
645                 break;
646         }
647 }
648
649
650 void TextClass::readOutputType(Lexer & lexrc)
651 {
652         LexerKeyword outputTypeTags[] = {
653                 { "docbook",  DOCBOOK },
654                 { "latex",    LATEX },
655                 { "literate", LITERATE }
656         };
657
658         PushPopHelper pph(lexrc, outputTypeTags);
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                 LYXERR0("Unhandled value " << le);
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         LASSERT(!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                 LASSERT(false, /**/);
946         }
947
948         return *it;
949 }
950
951
952 Layout & TextClass::operator[](docstring const & name)
953 {
954         LASSERT(!name.empty(), /**/);
955
956         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
957
958         if (it == end()) {
959                 LYXERR0("We failed to find the layout '" << to_utf8(name)
960                        << "' in the layout list. You MUST investigate!");
961                 for (const_iterator cit = begin(); cit != end(); ++cit)
962                         LYXERR0(" " << to_utf8(cit->name()));
963
964                 // we require the name to exist
965                 LASSERT(false, /**/);
966         }
967
968         return *it;
969 }
970
971
972 bool TextClass::deleteLayout(docstring const & name)
973 {
974         if (name == defaultLayoutName() || name == emptyLayoutName())
975                 return false;
976
977         LayoutList::iterator it =
978                 remove_if(layoutlist_.begin(), layoutlist_.end(),
979                           LayoutNamesEqual(name));
980
981         LayoutList::iterator end = layoutlist_.end();
982         bool const ret = (it != end);
983         layoutlist_.erase(it, end);
984         return ret;
985 }
986
987
988 // Load textclass info if not loaded yet
989 bool TextClass::load(string const & path) const
990 {
991         if (loaded_)
992                 return true;
993
994         // Read style-file, provided path is searched before the system ones
995         FileName layout_file;
996         if (!path.empty())
997                 layout_file = FileName(addName(path, name_ + ".layout"));
998         if (layout_file.empty() || !layout_file.exists())
999                 layout_file = libFileSearch("layouts", name_, "layout");
1000         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1001
1002         if (!loaded_) {
1003                 lyxerr << "Error reading `"
1004                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
1005                        << "'\n(Check `" << name_
1006                        << "')\nCheck your installation and "
1007                         "try Options/Reconfigure..." << endl;
1008         }
1009
1010         return loaded_;
1011 }
1012
1013
1014 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
1015 {
1016         docstring n = name;
1017         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1018         while (!n.empty()) {
1019                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1020                 if (cit != cen && cit->first == n)
1021                         return cit->second;
1022                 size_t i = n.find(':');
1023                 if (i == string::npos)
1024                         break;
1025                 n = n.substr(0,i);
1026         }
1027         return empty_insetlayout_;
1028 }
1029
1030
1031 docstring const & TextClass::defaultLayoutName() const
1032 {
1033         // This really should come from the actual layout... (Lgb)
1034         return defaultlayout_;
1035 }
1036
1037
1038 Layout const & TextClass::defaultLayout() const
1039 {
1040         return operator[](defaultLayoutName());
1041 }
1042
1043
1044 bool TextClass::isDefaultLayout(Layout const & layout) const 
1045 {
1046         return layout.name() == defaultLayoutName();
1047 }
1048
1049
1050 bool TextClass::isEmptyLayout(Layout const & layout) const 
1051 {
1052         return layout.name() == emptyLayoutName();
1053 }
1054
1055
1056 /////////////////////////////////////////////////////////////////////////
1057 //
1058 // DocumentClassBundle
1059 //
1060 /////////////////////////////////////////////////////////////////////////
1061
1062 DocumentClassBundle::~DocumentClassBundle()
1063 {
1064         for (size_t i = 0; i != documentClasses_.size(); ++i)
1065                 delete documentClasses_[i];
1066         documentClasses_.clear();
1067 }
1068
1069 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1070 {
1071         DocumentClass * dc = new DocumentClass(baseClass);
1072         documentClasses_.push_back(dc);
1073         return *documentClasses_.back();
1074 }
1075
1076
1077 DocumentClassBundle & DocumentClassBundle::get()
1078 {
1079         static DocumentClassBundle singleton; 
1080         return singleton; 
1081 }
1082
1083
1084 /////////////////////////////////////////////////////////////////////////
1085 //
1086 // DocumentClass
1087 //
1088 /////////////////////////////////////////////////////////////////////////
1089
1090 DocumentClass::DocumentClass(LayoutFile const & tc)
1091         : TextClass(tc)
1092 {}
1093
1094
1095 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1096 {
1097         LayoutList::const_iterator it  = layoutlist_.begin();
1098         LayoutList::const_iterator end = layoutlist_.end();
1099         for (; it != end; ++it)
1100                 if (it->latexname() == lay)
1101                         return true;
1102         return false;
1103 }
1104
1105
1106 bool DocumentClass::provides(string const & p) const
1107 {
1108         return provides_.find(p) != provides_.end();
1109 }
1110
1111
1112 bool DocumentClass::hasTocLevels() const
1113 {
1114         return min_toclevel_ != Layout::NOT_IN_TOC;
1115 }
1116
1117
1118 /////////////////////////////////////////////////////////////////////////
1119 //
1120 // PageSides
1121 //
1122 /////////////////////////////////////////////////////////////////////////
1123
1124 ostream & operator<<(ostream & os, PageSides p)
1125 {
1126         switch (p) {
1127         case OneSide:
1128                 os << '1';
1129                 break;
1130         case TwoSides:
1131                 os << '2';
1132                 break;
1133         }
1134         return os;
1135 }
1136
1137
1138 } // namespace lyx