]> git.lyx.org Git - features.git/blob - src/TextClass.cpp
next try...
[features.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, TITLE_ENVIRONMENT);
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, LITERATE);
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 enum ClassOptionsTags {
678         CO_FONTSIZE = 1,
679         CO_PAGESTYLE,
680         CO_OTHER,
681         CO_HEADER,
682         CO_END
683 };
684
685
686 void TextClass::readClassOptions(Lexer & lexrc)
687 {
688         LexerKeyword classOptionsTags[] = {
689                 {"end", CO_END },
690                 {"fontsize", CO_FONTSIZE },
691                 {"header", CO_HEADER },
692                 {"other", CO_OTHER },
693                 {"pagestyle", CO_PAGESTYLE }
694         };
695
696         lexrc.pushTable(classOptionsTags);
697         bool getout = false;
698         while (!getout && lexrc.isOK()) {
699                 int le = lexrc.lex();
700                 switch (le) {
701                 case Lexer::LEX_UNDEF:
702                         lexrc.printError("Unknown ClassOption tag `$$Token'");
703                         continue;
704                 default: break;
705                 }
706                 switch (static_cast<ClassOptionsTags>(le)) {
707                 case CO_FONTSIZE:
708                         lexrc.next();
709                         opt_fontsize_ = rtrim(lexrc.getString());
710                         break;
711                 case CO_PAGESTYLE:
712                         lexrc.next();
713                         opt_pagestyle_ = rtrim(lexrc.getString());
714                         break;
715                 case CO_OTHER:
716                         lexrc.next();
717                         options_ = lexrc.getString();
718                         break;
719                 case CO_HEADER:
720                         lexrc.next();
721                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
722                         break;
723                 case CO_END:
724                         getout = true;
725                         break;
726                 }
727         }
728         lexrc.popTable();
729 }
730
731
732 enum FloatTags {
733         FT_TYPE = 1,
734         FT_NAME,
735         FT_PLACEMENT,
736         FT_EXT,
737         FT_WITHIN,
738         FT_STYLE,
739         FT_LISTNAME,
740         FT_BUILTIN,
741         FT_END
742 };
743
744
745 void TextClass::readFloat(Lexer & lexrc)
746 {
747         LexerKeyword floatTags[] = {
748                 { "end", FT_END },
749                 { "extension", FT_EXT },
750                 { "guiname", FT_NAME },
751                 { "latexbuiltin", FT_BUILTIN },
752                 { "listname", FT_LISTNAME },
753                 { "numberwithin", FT_WITHIN },
754                 { "placement", FT_PLACEMENT },
755                 { "style", FT_STYLE },
756                 { "type", FT_TYPE }
757         };
758
759         lexrc.pushTable(floatTags);
760
761         string type;
762         string placement;
763         string ext;
764         string within;
765         string style;
766         string name;
767         string listName;
768         bool builtin = false;
769
770         bool getout = false;
771         while (!getout && lexrc.isOK()) {
772                 int le = lexrc.lex();
773                 switch (le) {
774                 case Lexer::LEX_UNDEF:
775                         lexrc.printError("Unknown float tag `$$Token'");
776                         continue;
777                 default: break;
778                 }
779                 switch (static_cast<FloatTags>(le)) {
780                 case FT_TYPE:
781                         lexrc.next();
782                         type = lexrc.getString();
783                         if (floatlist_.typeExist(type)) {
784                                 Floating const & fl = floatlist_.getType(type);
785                                 placement = fl.placement();
786                                 ext = fl.ext();
787                                 within = fl.within();
788                                 style = fl.style();
789                                 name = fl.name();
790                                 listName = fl.listName();
791                                 builtin = fl.builtin();
792                         } 
793                         break;
794                 case FT_NAME:
795                         lexrc.next();
796                         name = lexrc.getString();
797                         break;
798                 case FT_PLACEMENT:
799                         lexrc.next();
800                         placement = lexrc.getString();
801                         break;
802                 case FT_EXT:
803                         lexrc.next();
804                         ext = lexrc.getString();
805                         break;
806                 case FT_WITHIN:
807                         lexrc.next();
808                         within = lexrc.getString();
809                         if (within == "none")
810                                 within.erase();
811                         break;
812                 case FT_STYLE:
813                         lexrc.next();
814                         style = lexrc.getString();
815                         break;
816                 case FT_LISTNAME:
817                         lexrc.next();
818                         listName = lexrc.getString();
819                         break;
820                 case FT_BUILTIN:
821                         lexrc.next();
822                         builtin = lexrc.getBool();
823                         break;
824                 case FT_END:
825                         getout = true;
826                         break;
827                 }
828         }
829
830         // Here if have a full float if getout == true
831         if (getout) {
832                 Floating fl(type, placement, ext, within,
833                             style, name, listName, builtin);
834                 floatlist_.newFloat(fl);
835                 // each float has its own counter
836                 counters_.newCounter(from_ascii(type), from_ascii(within),
837                                       docstring(), docstring());
838                 // also define sub-float counters
839                 docstring const subtype = "sub-" + from_ascii(type);
840                 counters_.newCounter(subtype, from_ascii(type),
841                                       "\\alph{" + subtype + "}", docstring());
842         }
843
844         lexrc.popTable();
845 }
846
847
848 enum CounterTags {
849         CT_NAME = 1,
850         CT_WITHIN,
851         CT_LABELSTRING,
852         CT_LABELSTRING_APPENDIX,
853         CT_END
854 };
855
856
857 void TextClass::readCounter(Lexer & lexrc)
858 {
859         LexerKeyword counterTags[] = {
860                 { "end", CT_END },
861                 { "labelstring", CT_LABELSTRING },
862                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
863                 { "name", CT_NAME },
864                 { "within", CT_WITHIN }
865         };
866
867         lexrc.pushTable(counterTags);
868
869         docstring name;
870         docstring within;
871         docstring labelstring;
872         docstring labelstring_appendix;
873
874         bool getout = false;
875         while (!getout && lexrc.isOK()) {
876                 int le = lexrc.lex();
877                 switch (le) {
878                 case Lexer::LEX_UNDEF:
879                         lexrc.printError("Unknown counter tag `$$Token'");
880                         continue;
881                 default: break;
882                 }
883                 switch (static_cast<CounterTags>(le)) {
884                 case CT_NAME:
885                         lexrc.next();
886                         name = lexrc.getDocString();
887                         if (counters_.hasCounter(name))
888                                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
889                         else
890                                 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
891                         break;
892                 case CT_WITHIN:
893                         lexrc.next();
894                         within = lexrc.getDocString();
895                         if (within == "none")
896                                 within.erase();
897                         break;
898                 case CT_LABELSTRING:
899                         lexrc.next();
900                         labelstring = lexrc.getDocString();
901                         labelstring_appendix = labelstring;
902                         break;
903                 case CT_LABELSTRING_APPENDIX:
904                         lexrc.next();
905                         labelstring_appendix = lexrc.getDocString();
906                         break;
907                 case CT_END:
908                         getout = true;
909                         break;
910                 }
911         }
912
913         // Here if have a full counter if getout == true
914         if (getout)
915                 counters_.newCounter(name, within, 
916                                       labelstring, labelstring_appendix);
917
918         lexrc.popTable();
919 }
920
921
922 bool TextClass::hasLayout(docstring const & n) const
923 {
924         docstring const name = n.empty() ? defaultLayoutName() : n;
925
926         return find_if(layoutlist_.begin(), layoutlist_.end(),
927                        LayoutNamesEqual(name))
928                 != layoutlist_.end();
929 }
930
931
932
933 Layout const & TextClass::operator[](docstring const & name) const
934 {
935         BOOST_ASSERT(!name.empty());
936
937         const_iterator it = 
938                 find_if(begin(), end(), LayoutNamesEqual(name));
939
940         if (it == end()) {
941                 lyxerr << "We failed to find the layout '" << to_utf8(name)
942                        << "' in the layout list. You MUST investigate!"
943                        << endl;
944                 for (const_iterator cit = begin(); cit != end(); ++cit)
945                         lyxerr  << " " << to_utf8(cit->name()) << endl;
946
947                 // we require the name to exist
948                 BOOST_ASSERT(false);
949         }
950
951         return *it;
952 }
953
954
955 Layout & TextClass::operator[](docstring const & name)
956 {
957         BOOST_ASSERT(!name.empty());
958
959         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
960
961         if (it == end()) {
962                 lyxerr << "We failed to find the layout '" << to_utf8(name)
963                        << "' in the layout list. You MUST investigate!"
964                        << endl;
965                 for (const_iterator cit = begin(); cit != end(); ++cit)
966                         lyxerr  << " " << to_utf8(cit->name()) << endl;
967
968                 // we require the name to exist
969                 BOOST_ASSERT(false);
970         }
971
972         return *it;
973 }
974
975
976 bool TextClass::deleteLayout(docstring const & name)
977 {
978         if (name == defaultLayoutName() || name == emptyLayoutName())
979                 return false;
980
981         LayoutList::iterator it =
982                 remove_if(layoutlist_.begin(), layoutlist_.end(),
983                           LayoutNamesEqual(name));
984
985         LayoutList::iterator end = layoutlist_.end();
986         bool const ret = (it != end);
987         layoutlist_.erase(it, end);
988         return ret;
989 }
990
991
992 // Load textclass info if not loaded yet
993 bool TextClass::load(string const & path) const
994 {
995         if (loaded_)
996                 return true;
997
998         // Read style-file, provided path is searched before the system ones
999         FileName layout_file;
1000         if (!path.empty())
1001                 layout_file = FileName(addName(path, name_ + ".layout"));
1002         if (layout_file.empty() || !layout_file.exists())
1003                 layout_file = libFileSearch("layouts", name_, "layout");
1004         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1005
1006         if (!loaded_) {
1007                 lyxerr << "Error reading `"
1008                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
1009                        << "'\n(Check `" << name_
1010                        << "')\nCheck your installation and "
1011                         "try Options/Reconfigure..." << endl;
1012         }
1013
1014         return loaded_;
1015 }
1016
1017
1018 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
1019 {
1020         docstring n = name;
1021         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1022         while (!n.empty()) {
1023                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1024                 if (cit != cen && cit->first == n)
1025                         return cit->second;
1026                 size_t i = n.find(':');
1027                 if (i == string::npos)
1028                         break;
1029                 n = n.substr(0,i);
1030         }
1031         return empty_insetlayout_;
1032 }
1033
1034
1035 docstring const & TextClass::defaultLayoutName() const
1036 {
1037         // This really should come from the actual layout... (Lgb)
1038         return defaultlayout_;
1039 }
1040
1041
1042 Layout const & TextClass::defaultLayout() const
1043 {
1044         return operator[](defaultLayoutName());
1045 }
1046
1047
1048 bool TextClass::isDefaultLayout(Layout const & lay) const 
1049 {
1050         return lay.name() == defaultLayoutName();
1051 }
1052
1053
1054 bool TextClass::isEmptyLayout(Layout const & lay) const 
1055 {
1056         return lay.name() == emptyLayoutName();
1057 }
1058
1059
1060 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1061 {
1062         DocumentClass * dc = new DocumentClass(baseClass);
1063         tc_list_.push_back(dc);
1064         return *tc_list_.back();
1065 }
1066
1067
1068 DocumentClassBundle & DocumentClassBundle::get()
1069 {
1070         static DocumentClassBundle singleton; 
1071         return singleton; 
1072 }
1073
1074
1075 DocumentClass::DocumentClass(LayoutFile const & tc)
1076         : TextClass(tc)
1077 {}
1078
1079
1080 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1081 {
1082         LayoutList::const_iterator it  = layoutlist_.begin();
1083         LayoutList::const_iterator end = layoutlist_.end();
1084         for (; it != end; ++it)
1085                 if (it->latexname() == lay)
1086                         return true;
1087         return false;
1088 }
1089
1090
1091 bool DocumentClass::provides(string const & p) const
1092 {
1093         return provides_.find(p) != provides_.end();
1094 }
1095
1096
1097 bool DocumentClass::hasTocLevels() const
1098 {
1099         return min_toclevel_ != Layout::NOT_IN_TOC;
1100 }
1101
1102
1103 ostream & operator<<(ostream & os, PageSides p)
1104 {
1105         switch (p) {
1106         case OneSide:
1107                 os << '1';
1108                 break;
1109         case TwoSides:
1110                 os << '2';
1111                 break;
1112         }
1113         return os;
1114 }
1115
1116
1117 } // namespace lyx