]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
9b5ff07431fe9defbf570a5a4ea0e5bf703b2fd4
[lyx.git] / src / TextClass.cpp
1 /**
2  * \file TextClass.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author Angus Leeming
9  * \author John Levon
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "TextClass.h"
18
19 #include "LayoutFile.h"
20 #include "Color.h"
21 #include "Counters.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "Layout.h"
25 #include "Lexer.h"
26 #include "Font.h"
27
28 #include "frontends/alert.h"
29
30 #include "support/debug.h"
31 #include "support/ExceptionMessage.h"
32 #include "support/FileName.h"
33 #include "support/filetools.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36 #include "support/os.h"
37
38 #include <algorithm>
39 #include <fstream>
40 #include <sstream>
41
42 #include "boost/assert.hpp"
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48
49 namespace {
50
51 class LayoutNamesEqual : public unary_function<Layout, bool> {
52 public:
53         LayoutNamesEqual(docstring const & name)
54                 : name_(name)
55         {}
56         bool operator()(Layout const & c) const
57         {
58                 return c.name() == name_;
59         }
60 private:
61         docstring name_;
62 };
63
64
65 int const FORMAT = 6;
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("PlainLayout");
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         // a hack to make this available for translation
136         // i'm sure there must be a better way (rgh)
137         _("PlainLayout");
138 }
139
140
141 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
142 {
143         LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
144         if (!lay.read(lexrc, *this)) {
145                 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
146                 return false;
147         }
148         // Resolve fonts
149         lay.resfont = lay.font;
150         lay.resfont.realize(defaultfont_);
151         lay.reslabelfont = lay.labelfont;
152         lay.reslabelfont.realize(defaultfont_);
153         return true; // no errors
154 }
155
156
157 enum TextClassTags {
158         TC_OUTPUTTYPE = 1,
159         TC_INPUT,
160         TC_STYLE,
161         TC_DEFAULTSTYLE,
162         TC_INSETLAYOUT,
163         TC_ENVIRONMENT,
164         TC_NOSTYLE,
165         TC_COLUMNS,
166         TC_SIDES,
167         TC_PAGESTYLE,
168         TC_DEFAULTFONT,
169         TC_SECNUMDEPTH,
170         TC_TOCDEPTH,
171         TC_CLASSOPTIONS,
172         TC_PREAMBLE,
173         TC_PROVIDES,
174         TC_REQUIRES,
175         TC_LEFTMARGIN,
176         TC_RIGHTMARGIN,
177         TC_FLOAT,
178         TC_COUNTER,
179         TC_NOFLOAT,
180         TC_TITLELATEXNAME,
181         TC_TITLELATEXTYPE,
182         TC_FORMAT
183 };
184
185
186 namespace {
187
188         keyword_item textClassTags[] = {
189                 { "classoptions",    TC_CLASSOPTIONS },
190                 { "columns",         TC_COLUMNS },
191                 { "counter",         TC_COUNTER },
192                 { "defaultfont",     TC_DEFAULTFONT },
193                 { "defaultstyle",    TC_DEFAULTSTYLE },
194                 { "environment",     TC_ENVIRONMENT },
195                 { "float",           TC_FLOAT },
196                 { "format",          TC_FORMAT },
197                 { "input",           TC_INPUT },
198                 { "insetlayout",     TC_INSETLAYOUT },
199                 { "leftmargin",      TC_LEFTMARGIN },
200                 { "nofloat",         TC_NOFLOAT },
201                 { "nostyle",         TC_NOSTYLE },
202                 { "outputtype",      TC_OUTPUTTYPE },
203                 { "pagestyle",       TC_PAGESTYLE },
204                 { "preamble",        TC_PREAMBLE },
205                 { "provides",        TC_PROVIDES },
206                 { "requires",        TC_REQUIRES },
207                 { "rightmargin",     TC_RIGHTMARGIN },
208                 { "secnumdepth",     TC_SECNUMDEPTH },
209                 { "sides",           TC_SIDES },
210                 { "style",           TC_STYLE },
211                 { "titlelatexname",  TC_TITLELATEXNAME },
212                 { "titlelatextype",  TC_TITLELATEXTYPE },
213                 { "tocdepth",        TC_TOCDEPTH }
214         };
215         
216 } //namespace anon
217
218
219 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
220 {
221         LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
222                 FileName const tempfile = FileName::tempName();
223                 bool success = layout2layout(filename, tempfile);
224                 if (success)
225                         success = read(tempfile, rt);
226                 tempfile.removeFile();
227                 return success;
228 }
229
230 bool TextClass::read(FileName const & filename, ReadType rt)
231 {
232         if (!filename.isReadableFile()) {
233                 lyxerr << "Cannot read layout file `" << filename << "'."
234                        << endl;
235                 return false;
236         }
237
238         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
239                 to_utf8(makeDisplayPath(filename.absFilename())));
240
241         // Define the `empty' layout used in table cells, ert, etc. Note that 
242         // we do this before loading any layout file, so that classes can 
243         // override features of this layout if they should choose to do so.
244         if (rt == BASECLASS && !hasLayout(emptylayout_)) {
245                 static char const * s = "Margin Static\n"
246                         "LatexType Paragraph\n"
247                         "LatexName dummy\n"
248                         "Align Block\n"
249                         "AlignPossible Left, Right, Center\n"
250                         "LabelType No_Label\n"
251                         "End";
252                 istringstream ss(s);
253                 Lexer lex(textClassTags, sizeof(textClassTags) / sizeof(textClassTags[0]));
254                 lex.setStream(ss);
255                 Layout lay;
256                 lay.setName(emptylayout_);
257                 if (!readStyle(lex, lay)) {
258                         // The only way this happens is because the hardcoded layout above
259                         // is wrong.
260                         BOOST_ASSERT(false);
261                 };
262                 layoutlist_.push_back(lay);
263         }
264         Lexer lexrc(textClassTags,
265                 sizeof(textClassTags) / sizeof(textClassTags[0]));
266
267         lexrc.setFile(filename);
268         ReturnValues retval = read(lexrc, rt);
269         
270         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
271                         to_utf8(makeDisplayPath(filename.absFilename())));
272         
273         if (retval != FORMAT_MISMATCH) 
274                 return retval == OK;
275         
276         bool const worx = convertLayoutFormat(filename, rt);
277         if (!worx) {
278                 lyxerr << "Unable to convert " << filename << 
279                         " to format " << FORMAT << std::endl;
280                 return false;
281         }
282         return true;
283 }
284
285
286 bool TextClass::validate(std::string const & str)
287 {
288         TextClass tc;
289         return tc.read(str, VALIDATION);
290 }
291
292
293 bool TextClass::read(std::string const & str, ReadType rt) 
294 {
295         Lexer lexrc(textClassTags,
296                 sizeof(textClassTags) / sizeof(textClassTags[0]));
297         istringstream is(str);
298         lexrc.setStream(is);
299         ReturnValues retval = read(lexrc, rt);
300
301         if (retval != FORMAT_MISMATCH) 
302                 return retval == OK;
303
304         // write the layout string to a temporary file
305         FileName const tempfile = FileName::tempName();
306         ofstream os(tempfile.toFilesystemEncoding().c_str());
307         if (!os) {
308                 lyxerr << "Unable to create tempoary file in TextClass::read!!" 
309                         << std::endl;
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                 lyxerr << "Unable to convert internal layout information to format " 
319                         << FORMAT << std::endl;
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_ENVIRONMENT:
388                 case TC_STYLE:
389                         if (lexrc.next()) {
390                                 docstring const name = from_utf8(subst(lexrc.getString(),
391                                                     '_', ' '));
392                                 if (name.empty()) {
393                                         string s = "Could not read name for style: `$$Token' "
394                                                 + lexrc.getString() + " is probably not valid UTF-8!";
395                                         lexrc.printError(s.c_str());
396                                         Layout lay;
397                                         // Since we couldn't read the name, we just scan the rest
398                                         // of the style and discard it.
399                                         error = !readStyle(lexrc, lay);
400                                 } else if (hasLayout(name)) {
401                                         Layout & lay = operator[](name);
402                                         error = !readStyle(lexrc, lay);
403                                 } else {
404                                         Layout lay;
405                                         lay.setName(name);
406                                         if (le == TC_ENVIRONMENT)
407                                                 lay.is_environment = true;
408                                         error = !readStyle(lexrc, lay);
409                                         if (!error)
410                                                 layoutlist_.push_back(lay);
411
412                                         if (defaultlayout_.empty()) {
413                                                 // We do not have a default layout yet, so we choose
414                                                 // the first layout we encounter.
415                                                 defaultlayout_ = name;
416                                         }
417                                 }
418                         }
419                         else {
420                                 //FIXME Should we also eat the style here? viz:
421                                 //Layout lay;
422                                 //readStyle(lexrc, lay);
423                                 //as above...
424                                 lexrc.printError("No name given for style: `$$Token'.");
425                                 error = true;
426                         }
427                         break;
428
429                 case TC_NOSTYLE:
430                         if (lexrc.next()) {
431                                 docstring const style = from_utf8(subst(lexrc.getString(),
432                                                      '_', ' '));
433                                 if (!deleteLayout(style))
434                                         lyxerr << "Cannot delete style `"
435                                                << to_utf8(style) << '\'' << endl;
436                         }
437                         break;
438
439                 case TC_COLUMNS:
440                         if (lexrc.next())
441                                 columns_ = lexrc.getInteger();
442                         break;
443
444                 case TC_SIDES:
445                         if (lexrc.next()) {
446                                 switch (lexrc.getInteger()) {
447                                 case 1: sides_ = OneSide; break;
448                                 case 2: sides_ = TwoSides; break;
449                                 default:
450                                         lyxerr << "Impossible number of page"
451                                                 " sides, setting to one."
452                                                << endl;
453                                         sides_ = OneSide;
454                                         break;
455                                 }
456                         }
457                         break;
458
459                 case TC_PAGESTYLE:
460                         lexrc.next();
461                         pagestyle_ = rtrim(lexrc.getString());
462                         break;
463
464                 case TC_DEFAULTFONT:
465                         defaultfont_ = lyxRead(lexrc);
466                         if (!defaultfont_.resolved()) {
467                                 lexrc.printError("Warning: defaultfont should "
468                                                  "be fully instantiated!");
469                                 defaultfont_.realize(sane_font);
470                         }
471                         break;
472
473                 case TC_SECNUMDEPTH:
474                         lexrc.next();
475                         secnumdepth_ = lexrc.getInteger();
476                         break;
477
478                 case TC_TOCDEPTH:
479                         lexrc.next();
480                         tocdepth_ = lexrc.getInteger();
481                         break;
482
483                 // First step to support options
484                 case TC_CLASSOPTIONS:
485                         readClassOptions(lexrc);
486                         break;
487
488                 case TC_PREAMBLE:
489                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
490                         break;
491
492                 case TC_PROVIDES: {
493                         lexrc.next();
494                         string const feature = lexrc.getString();
495                         lexrc.next();
496                         if (lexrc.getInteger())
497                                 provides_.insert(feature);
498                         else
499                                 provides_.erase(feature);
500                         break;
501                 }
502
503                 case TC_REQUIRES: {
504                         lexrc.eatLine();
505                         vector<string> const req 
506                                 = getVectorFromString(lexrc.getString());
507                         requires_.insert(req.begin(), req.end());
508                         break;
509                 }
510
511                 case TC_LEFTMARGIN:     // left margin type
512                         if (lexrc.next())
513                                 leftmargin_ = lexrc.getDocString();
514                         break;
515
516                 case TC_RIGHTMARGIN:    // right margin type
517                         if (lexrc.next())
518                                 rightmargin_ = lexrc.getDocString();
519                         break;
520
521                 case TC_INSETLAYOUT:
522                         if (lexrc.next()) {
523                                 InsetLayout il;
524                                 if (il.read(lexrc)) {
525                                         insetlayoutlist_[il.name()] = il;
526                                 }
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                 lyxerr << "Error: Textclass '" << name_
570                                                 << "' is missing a defaultstyle." << endl;
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         keyword_item titleTypeTags[] = {
623                 { "commandafter", TITLE_COMMAND_AFTER },
624                 { "environment", TITLE_ENVIRONMENT }
625         };
626
627         PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
628
629         int le = lexrc.lex();
630         switch (le) {
631         case Lexer::LEX_UNDEF:
632                 lexrc.printError("Unknown output type `$$Token'");
633                 return;
634         case TITLE_COMMAND_AFTER:
635         case TITLE_ENVIRONMENT:
636                 titletype_ = static_cast<TitleLatexType>(le);
637                 break;
638         default:
639                 lyxerr << "Unhandled value " << le
640                        << " in TextClass::readTitleType." << endl;
641
642                 break;
643         }
644 }
645
646
647 void TextClass::readOutputType(Lexer & lexrc)
648 {
649         keyword_item outputTypeTags[] = {
650                 { "docbook", DOCBOOK },
651                 { "latex", LATEX },
652                 { "literate", LITERATE }
653         };
654
655         PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
656
657         int le = lexrc.lex();
658         switch (le) {
659         case Lexer::LEX_UNDEF:
660                 lexrc.printError("Unknown output type `$$Token'");
661                 return;
662         case LATEX:
663         case DOCBOOK:
664         case LITERATE:
665                 outputType_ = static_cast<OutputType>(le);
666                 break;
667         default:
668                 lyxerr << "Unhandled value " << le
669                        << " in TextClass::readOutputType." << endl;
670
671                 break;
672         }
673 }
674
675
676 enum ClassOptionsTags {
677         CO_FONTSIZE = 1,
678         CO_PAGESTYLE,
679         CO_OTHER,
680         CO_HEADER,
681         CO_END
682 };
683
684
685 void TextClass::readClassOptions(Lexer & lexrc)
686 {
687         keyword_item 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, CO_END);
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 (static_cast<ClassOptionsTags>(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 enum FloatTags {
732         FT_TYPE = 1,
733         FT_NAME,
734         FT_PLACEMENT,
735         FT_EXT,
736         FT_WITHIN,
737         FT_STYLE,
738         FT_LISTNAME,
739         FT_BUILTIN,
740         FT_END
741 };
742
743
744 void TextClass::readFloat(Lexer & lexrc)
745 {
746         keyword_item floatTags[] = {
747                 { "end", FT_END },
748                 { "extension", FT_EXT },
749                 { "guiname", FT_NAME },
750                 { "latexbuiltin", FT_BUILTIN },
751                 { "listname", FT_LISTNAME },
752                 { "numberwithin", FT_WITHIN },
753                 { "placement", FT_PLACEMENT },
754                 { "style", FT_STYLE },
755                 { "type", FT_TYPE }
756         };
757
758         lexrc.pushTable(floatTags, FT_END);
759
760         string type;
761         string placement;
762         string ext;
763         string within;
764         string style;
765         string name;
766         string listName;
767         bool builtin = false;
768
769         bool getout = false;
770         while (!getout && lexrc.isOK()) {
771                 int le = lexrc.lex();
772                 switch (le) {
773                 case Lexer::LEX_UNDEF:
774                         lexrc.printError("Unknown float tag `$$Token'");
775                         continue;
776                 default: break;
777                 }
778                 switch (static_cast<FloatTags>(le)) {
779                 case FT_TYPE:
780                         lexrc.next();
781                         type = lexrc.getString();
782                         if (floatlist_.typeExist(type)) {
783                                 Floating const & fl = floatlist_.getType(type);
784                                 placement = fl.placement();
785                                 ext = fl.ext();
786                                 within = fl.within();
787                                 style = fl.style();
788                                 name = fl.name();
789                                 listName = fl.listName();
790                                 builtin = fl.builtin();
791                         } 
792                         break;
793                 case FT_NAME:
794                         lexrc.next();
795                         name = lexrc.getString();
796                         break;
797                 case FT_PLACEMENT:
798                         lexrc.next();
799                         placement = lexrc.getString();
800                         break;
801                 case FT_EXT:
802                         lexrc.next();
803                         ext = lexrc.getString();
804                         break;
805                 case FT_WITHIN:
806                         lexrc.next();
807                         within = lexrc.getString();
808                         if (within == "none")
809                                 within.erase();
810                         break;
811                 case FT_STYLE:
812                         lexrc.next();
813                         style = lexrc.getString();
814                         break;
815                 case FT_LISTNAME:
816                         lexrc.next();
817                         listName = lexrc.getString();
818                         break;
819                 case FT_BUILTIN:
820                         lexrc.next();
821                         builtin = lexrc.getBool();
822                         break;
823                 case FT_END:
824                         getout = true;
825                         break;
826                 }
827         }
828
829         // Here if have a full float if getout == true
830         if (getout) {
831                 Floating fl(type, placement, ext, within,
832                             style, name, listName, builtin);
833                 floatlist_.newFloat(fl);
834                 // each float has its own counter
835                 counters_.newCounter(from_ascii(type), from_ascii(within),
836                                       docstring(), docstring());
837                 // also define sub-float counters
838                 docstring const subtype = "sub-" + from_ascii(type);
839                 counters_.newCounter(subtype, from_ascii(type),
840                                       "\\alph{" + subtype + "}", docstring());
841         }
842
843         lexrc.popTable();
844 }
845
846
847 enum CounterTags {
848         CT_NAME = 1,
849         CT_WITHIN,
850         CT_LABELSTRING,
851         CT_LABELSTRING_APPENDIX,
852         CT_END
853 };
854
855
856 void TextClass::readCounter(Lexer & lexrc)
857 {
858         keyword_item counterTags[] = {
859                 { "end", CT_END },
860                 { "labelstring", CT_LABELSTRING },
861                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
862                 { "name", CT_NAME },
863                 { "within", CT_WITHIN }
864         };
865
866         lexrc.pushTable(counterTags, CT_END);
867
868         docstring name;
869         docstring within;
870         docstring labelstring;
871         docstring labelstring_appendix;
872
873         bool getout = false;
874         while (!getout && lexrc.isOK()) {
875                 int le = lexrc.lex();
876                 switch (le) {
877                 case Lexer::LEX_UNDEF:
878                         lexrc.printError("Unknown counter tag `$$Token'");
879                         continue;
880                 default: break;
881                 }
882                 switch (static_cast<CounterTags>(le)) {
883                 case CT_NAME:
884                         lexrc.next();
885                         name = lexrc.getDocString();
886                         if (counters_.hasCounter(name))
887                                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
888                         else
889                                 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
890                         break;
891                 case CT_WITHIN:
892                         lexrc.next();
893                         within = lexrc.getDocString();
894                         if (within == "none")
895                                 within.erase();
896                         break;
897                 case CT_LABELSTRING:
898                         lexrc.next();
899                         labelstring = lexrc.getDocString();
900                         labelstring_appendix = labelstring;
901                         break;
902                 case CT_LABELSTRING_APPENDIX:
903                         lexrc.next();
904                         labelstring_appendix = lexrc.getDocString();
905                         break;
906                 case CT_END:
907                         getout = true;
908                         break;
909                 }
910         }
911
912         // Here if have a full counter if getout == true
913         if (getout)
914                 counters_.newCounter(name, within, 
915                                       labelstring, labelstring_appendix);
916
917         lexrc.popTable();
918 }
919
920
921 bool TextClass::hasLayout(docstring const & n) const
922 {
923         docstring const name = n.empty() ? defaultLayoutName() : n;
924
925         return find_if(layoutlist_.begin(), layoutlist_.end(),
926                        LayoutNamesEqual(name))
927                 != layoutlist_.end();
928 }
929
930
931
932 Layout const & TextClass::operator[](docstring const & name) const
933 {
934         BOOST_ASSERT(!name.empty());
935
936         const_iterator it = 
937                 find_if(begin(), end(), LayoutNamesEqual(name));
938
939         if (it == end()) {
940                 lyxerr << "We failed to find the layout '" << to_utf8(name)
941                        << "' in the layout list. You MUST investigate!"
942                        << endl;
943                 for (const_iterator cit = begin(); cit != end(); ++cit)
944                         lyxerr  << " " << to_utf8(cit->name()) << endl;
945
946                 // we require the name to exist
947                 BOOST_ASSERT(false);
948         }
949
950         return *it;
951 }
952
953
954 Layout & TextClass::operator[](docstring const & name)
955 {
956         BOOST_ASSERT(!name.empty());
957
958         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
959
960         if (it == end()) {
961                 lyxerr << "We failed to find the layout '" << to_utf8(name)
962                        << "' in the layout list. You MUST investigate!"
963                        << endl;
964                 for (const_iterator cit = begin(); cit != end(); ++cit)
965                         lyxerr  << " " << to_utf8(cit->name()) << endl;
966
967                 // we require the name to exist
968                 BOOST_ASSERT(false);
969         }
970
971         return *it;
972 }
973
974
975 bool TextClass::deleteLayout(docstring const & name)
976 {
977         if (name == defaultLayoutName() || name == emptyLayoutName())
978                 return false;
979
980         LayoutList::iterator it =
981                 remove_if(layoutlist_.begin(), layoutlist_.end(),
982                           LayoutNamesEqual(name));
983
984         LayoutList::iterator end = layoutlist_.end();
985         bool const ret = (it != end);
986         layoutlist_.erase(it, end);
987         return ret;
988 }
989
990
991 // Load textclass info if not loaded yet
992 bool TextClass::load(string const & path) const
993 {
994         if (loaded_)
995                 return true;
996
997         // Read style-file, provided path is searched before the system ones
998         FileName layout_file;
999         if (!path.empty())
1000                 layout_file = FileName(addName(path, name_ + ".layout"));
1001         if (layout_file.empty() || !layout_file.exists())
1002                 layout_file = libFileSearch("layouts", name_, "layout");
1003         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1004
1005         if (!loaded_) {
1006                 lyxerr << "Error reading `"
1007                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
1008                        << "'\n(Check `" << name_
1009                        << "')\nCheck your installation and "
1010                         "try Options/Reconfigure..." << endl;
1011         }
1012
1013         return loaded_;
1014 }
1015
1016
1017 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
1018 {
1019         docstring n = name;
1020         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1021         while (!n.empty()) {
1022                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1023                 if (cit != cen && cit->first == n)
1024                         return cit->second;
1025                 size_t i = n.find(':');
1026                 if (i == string::npos)
1027                         break;
1028                 n = n.substr(0,i);
1029         }
1030         return empty_insetlayout_;
1031 }
1032
1033
1034 docstring const & TextClass::defaultLayoutName() const
1035 {
1036         // This really should come from the actual layout... (Lgb)
1037         return defaultlayout_;
1038 }
1039
1040
1041 Layout const & TextClass::defaultLayout() const
1042 {
1043         return operator[](defaultLayoutName());
1044 }
1045
1046
1047 bool TextClass::isDefaultLayout(Layout const & lay) const 
1048 {
1049         return lay.name() == defaultLayoutName();
1050 }
1051
1052
1053 bool TextClass::isEmptyLayout(Layout const & lay) const 
1054 {
1055         return lay.name() == emptyLayoutName();
1056 }
1057
1058
1059 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1060 {
1061         DocumentClass * dc = new DocumentClass(baseClass);
1062         tc_list_.push_back(dc);
1063         return *tc_list_.back();
1064 }
1065
1066
1067 DocumentClassBundle & DocumentClassBundle::get()
1068 {
1069         static DocumentClassBundle singleton; 
1070         return singleton; 
1071 }
1072
1073
1074 DocumentClass::DocumentClass(LayoutFile const & tc)
1075         : TextClass(tc)
1076 {}
1077
1078
1079 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1080 {
1081         LayoutList::const_iterator it  = layoutlist_.begin();
1082         LayoutList::const_iterator end = layoutlist_.end();
1083         for (; it != end; ++it)
1084                 if (it->latexname() == lay)
1085                         return true;
1086         return false;
1087 }
1088
1089
1090 bool DocumentClass::provides(string const & p) const
1091 {
1092         return provides_.find(p) != provides_.end();
1093 }
1094
1095
1096 bool DocumentClass::hasTocLevels() const
1097 {
1098         return min_toclevel_ != Layout::NOT_IN_TOC;
1099 }
1100
1101
1102 ostream & operator<<(ostream & os, PageSides p)
1103 {
1104         switch (p) {
1105         case OneSide:
1106                 os << '1';
1107                 break;
1108         case TwoSides:
1109                 os << '2';
1110                 break;
1111         }
1112         return os;
1113 }
1114
1115
1116 } // namespace lyx