]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
cosmetics
[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 <sstream>
40
41 #include "boost/assert.hpp"
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 = 6;
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                 lyxerr << "Could not find layout conversion "
72                           "script layout2layout.py." << endl;
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 =
85                 runCommand(command_str);
86         if (ret.first != 0) {
87                 lyxerr << "Could not run layout conversion "
88                           "script layout2layout.py." << endl;
89                 return false;
90         }
91         return true;
92 }
93
94
95 std::string translateRT(TextClass::ReadType rt) 
96 {
97         switch (rt) {
98         case TextClass::BASECLASS:
99                 return "textclass";
100         case TextClass::MERGE:
101                 return "input file";
102         case TextClass::MODULE:
103                 return "module file";
104         }
105         // shutup warning
106         return string();
107 }
108
109 } // namespace anon
110
111
112 docstring const TextClass::emptylayout_ = from_ascii("PlainLayout");
113
114
115 InsetLayout DocumentClass::empty_insetlayout_;
116
117
118 TextClass::TextClass()
119 {
120         outputType_ = LATEX;
121         columns_ = 1;
122         sides_ = OneSide;
123         secnumdepth_ = 3;
124         tocdepth_ = 3;
125         pagestyle_ = "default";
126         defaultfont_ = sane_font;
127         opt_fontsize_ = "10|11|12";
128         opt_pagestyle_ = "empty|plain|headings|fancy";
129         titletype_ = TITLE_COMMAND_AFTER;
130         titlename_ = "maketitle";
131         loaded_ = false;
132         // a hack to make this available for translation
133         // i'm sure there must be a better way (rgh)
134         _("PlainLayout");
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 };
181
182
183 // Reads a textclass structure from file.
184 bool TextClass::read(FileName const & filename, ReadType rt)
185 {
186         if (!filename.isReadableFile()) {
187                 lyxerr << "Cannot read layout file `" << filename << "'."
188                        << endl;
189                 return false;
190         }
191
192         keyword_item textClassTags[] = {
193                 { "classoptions",    TC_CLASSOPTIONS },
194                 { "columns",         TC_COLUMNS },
195                 { "counter",         TC_COUNTER },
196                 { "defaultfont",     TC_DEFAULTFONT },
197                 { "defaultstyle",    TC_DEFAULTSTYLE },
198                 { "environment",     TC_ENVIRONMENT },
199                 { "float",           TC_FLOAT },
200                 { "format",          TC_FORMAT },
201                 { "input",           TC_INPUT },
202                 { "insetlayout",     TC_INSETLAYOUT },
203                 { "leftmargin",      TC_LEFTMARGIN },
204                 { "nofloat",         TC_NOFLOAT },
205                 { "nostyle",         TC_NOSTYLE },
206                 { "outputtype",      TC_OUTPUTTYPE },
207                 { "pagestyle",       TC_PAGESTYLE },
208                 { "preamble",        TC_PREAMBLE },
209                 { "provides",        TC_PROVIDES },
210                 { "requires",        TC_REQUIRES },
211                 { "rightmargin",     TC_RIGHTMARGIN },
212                 { "secnumdepth",     TC_SECNUMDEPTH },
213                 { "sides",           TC_SIDES },
214                 { "style",           TC_STYLE },
215                 { "titlelatexname",  TC_TITLELATEXNAME },
216                 { "titlelatextype",  TC_TITLELATEXTYPE },
217                 { "tocdepth",        TC_TOCDEPTH }
218         };
219
220         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
221                 to_utf8(makeDisplayPath(filename.absFilename())));
222
223         // Define the `empty' layout used in table cells, ert, etc. Note that 
224         // we do this before loading any layout file, so that classes can 
225         // override features of this layout if they should choose to do so.
226         if (rt == BASECLASS) {
227                 static char const * s = "Margin Static\n"
228                         "LatexType Paragraph\n"
229                         "LatexName dummy\n"
230                         "Align Block\n"
231                         "AlignPossible Left, Right, Center\n"
232                         "LabelType No_Label\n"
233                         "End";
234                 istringstream ss(s);
235                 Lexer lex(textClassTags, sizeof(textClassTags) / sizeof(textClassTags[0]));
236                 lex.setStream(ss);
237                 Layout lay;
238                 lay.setName(emptylayout_);
239                 if (!readStyle(lex, lay)) {
240                         // The only way this happens is because the hardcoded layout above
241                         // is wrong.
242                         BOOST_ASSERT(false);
243                 };
244                 layoutlist_.push_back(lay);
245         }
246
247         Lexer lexrc(textClassTags,
248                 sizeof(textClassTags) / sizeof(textClassTags[0]));
249
250         lexrc.setFile(filename);
251         bool error = !lexrc.isOK();
252
253         // Format of files before the 'Format' tag was introduced
254         int format = 1;
255
256         // parsing
257         while (lexrc.isOK() && !error) {
258                 int le = lexrc.lex();
259
260                 switch (le) {
261                 case Lexer::LEX_FEOF:
262                         continue;
263
264                 case Lexer::LEX_UNDEF:
265                         lexrc.printError("Unknown TextClass tag `$$Token'");
266                         error = true;
267                         continue;
268
269                 default:
270                         break;
271                 }
272
273                 switch (static_cast<TextClassTags>(le)) {
274
275                 case TC_FORMAT:
276                         if (lexrc.next())
277                                 format = lexrc.getInteger();
278                         break;
279
280                 case TC_OUTPUTTYPE:   // output type definition
281                         readOutputType(lexrc);
282                         break;
283
284                 case TC_INPUT: // Include file
285                         if (lexrc.next()) {
286                                 string const inc = lexrc.getString();
287                                 FileName tmp = libFileSearch("layouts", inc,
288                                                             "layout");
289
290                                 if (tmp.empty()) {
291                                         lexrc.printError("Could not find input file: " + inc);
292                                         error = true;
293                                 } else if (!read(tmp, MERGE)) {
294                                         lexrc.printError("Error reading input"
295                                                          "file: " + tmp.absFilename());
296                                         error = true;
297                                 }
298                         }
299                         break;
300
301                 case TC_DEFAULTSTYLE:
302                         if (lexrc.next()) {
303                                 docstring const name = from_utf8(subst(lexrc.getString(),
304                                                           '_', ' '));
305                                 defaultlayout_ = name;
306                         }
307                         break;
308
309                 case TC_ENVIRONMENT:
310                 case TC_STYLE:
311                         if (lexrc.next()) {
312                                 docstring const name = from_utf8(subst(lexrc.getString(),
313                                                     '_', ' '));
314                                 if (name.empty()) {
315                                         string s = "Could not read name for style: `$$Token' "
316                                                 + lexrc.getString() + " is probably not valid UTF-8!";
317                                         lexrc.printError(s.c_str());
318                                         Layout lay;
319                                         //FIXME If we're just dropping this layout, do we really
320                                         //care whether there's an error?? Or should we just set
321                                         //error to true, since we couldn't even read the name?
322                                         error = !readStyle(lexrc, lay);
323                                 } else if (hasLayout(name)) {
324                                         Layout & lay = operator[](name);
325                                         error = !readStyle(lexrc, lay);
326                                 } else {
327                                         Layout lay;
328                                         lay.setName(name);
329                                         if (le == TC_ENVIRONMENT)
330                                                 lay.is_environment = true;
331                                         error = !readStyle(lexrc, lay);
332                                         if (!error)
333                                                 layoutlist_.push_back(lay);
334
335                                         if (defaultlayout_.empty()) {
336                                                 // We do not have a default layout yet, so we choose
337                                                 // the first layout we encounter.
338                                                 defaultlayout_ = name;
339                                         }
340                                 }
341                         }
342                         else {
343                                 //FIXME Should we also eat the style here? viz:
344                                 //Layout lay;
345                                 //readStyle(lexrc, lay);
346                                 //as above...
347                                 lexrc.printError("No name given for style: `$$Token'.");
348                                 error = true;
349                         }
350                         break;
351
352                 case TC_NOSTYLE:
353                         if (lexrc.next()) {
354                                 docstring const style = from_utf8(subst(lexrc.getString(),
355                                                      '_', ' '));
356                                 if (!deleteLayout(style))
357                                         lyxerr << "Cannot delete style `"
358                                                << to_utf8(style) << '\'' << endl;
359                         }
360                         break;
361
362                 case TC_COLUMNS:
363                         if (lexrc.next())
364                                 columns_ = lexrc.getInteger();
365                         break;
366
367                 case TC_SIDES:
368                         if (lexrc.next()) {
369                                 switch (lexrc.getInteger()) {
370                                 case 1: sides_ = OneSide; break;
371                                 case 2: sides_ = TwoSides; break;
372                                 default:
373                                         lyxerr << "Impossible number of page"
374                                                 " sides, setting to one."
375                                                << endl;
376                                         sides_ = OneSide;
377                                         break;
378                                 }
379                         }
380                         break;
381
382                 case TC_PAGESTYLE:
383                         lexrc.next();
384                         pagestyle_ = rtrim(lexrc.getString());
385                         break;
386
387                 case TC_DEFAULTFONT:
388                         defaultfont_ = lyxRead(lexrc);
389                         if (!defaultfont_.resolved()) {
390                                 lexrc.printError("Warning: defaultfont should "
391                                                  "be fully instantiated!");
392                                 defaultfont_.realize(sane_font);
393                         }
394                         break;
395
396                 case TC_SECNUMDEPTH:
397                         lexrc.next();
398                         secnumdepth_ = lexrc.getInteger();
399                         break;
400
401                 case TC_TOCDEPTH:
402                         lexrc.next();
403                         tocdepth_ = lexrc.getInteger();
404                         break;
405
406                 // First step to support options
407                 case TC_CLASSOPTIONS:
408                         readClassOptions(lexrc);
409                         break;
410
411                 case TC_PREAMBLE:
412                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
413                         break;
414
415                 case TC_PROVIDES: {
416                         lexrc.next();
417                         string const feature = lexrc.getString();
418                         lexrc.next();
419                         if (lexrc.getInteger())
420                                 provides_.insert(feature);
421                         else
422                                 provides_.erase(feature);
423                         break;
424                 }
425
426                 case TC_REQUIRES: {
427                         lexrc.eatLine();
428                         vector<string> const req 
429                                 = getVectorFromString(lexrc.getString());
430                         requires_.insert(req.begin(), req.end());
431                         break;
432                 }
433
434                 case TC_LEFTMARGIN:     // left margin type
435                         if (lexrc.next())
436                                 leftmargin_ = lexrc.getDocString();
437                         break;
438
439                 case TC_RIGHTMARGIN:    // right margin type
440                         if (lexrc.next())
441                                 rightmargin_ = lexrc.getDocString();
442                         break;
443
444                 case TC_INSETLAYOUT:
445                         if (lexrc.next()) {
446                                 InsetLayout il;
447                                 if (il.read(lexrc)) {
448                                         insetlayoutlist_[il.name()] = il;
449                                 }
450                                 // else there was an error, so forget it
451                         }
452                         break;
453
454                 case TC_FLOAT:
455                         readFloat(lexrc);
456                         break;
457
458                 case TC_COUNTER:
459                         readCounter(lexrc);
460                         break;
461
462                 case TC_TITLELATEXTYPE:
463                         readTitleType(lexrc);
464                         break;
465
466                 case TC_TITLELATEXNAME:
467                         if (lexrc.next())
468                                 titlename_ = lexrc.getString();
469                         break;
470
471                 case TC_NOFLOAT:
472                         if (lexrc.next()) {
473                                 string const nofloat = lexrc.getString();
474                                 floatlist_.erase(nofloat);
475                         }
476                         break;
477                 }
478
479                 //Note that this is triggered the first time through the loop unless
480                 //we hit a format tag.
481                 if (format != FORMAT)
482                         break;
483         }
484
485         if (format != FORMAT) {
486                 LYXERR(Debug::TCLASS, "Converting layout file from format "
487                                       << format << " to " << FORMAT);
488                 FileName const tempfile = FileName::tempName();
489                 bool success = layout2layout(filename, tempfile);
490                 if (success)
491                          read(tempfile, rt);
492                 tempfile.removeFile();
493                 return success;
494         }
495
496         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
497                         to_utf8(makeDisplayPath(filename.absFilename())));
498
499         if (rt != BASECLASS) 
500                 return !error;
501
502         if (defaultlayout_.empty()) {
503                 lyxerr << "Error: Textclass '" << name_
504                                                 << "' is missing a defaultstyle." << endl;
505                 error = true;
506         }
507                 
508         //Try to erase "stdinsets" from the provides_ set. 
509         //The
510         //  Provides stdinsets 1
511         //declaration simply tells us that the standard insets have been
512         //defined. (It's found in stdinsets.inc but could also be used in
513         //user-defined files.) There isn't really any such package. So we
514         //might as well go ahead and erase it.
515         //If we do not succeed, then it was not there, which means that
516         //the textclass did not provide the definitions of the standard
517         //insets. So we need to try to load them.
518         int erased = provides_.erase("stdinsets");
519         if (!erased) {
520                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
521
522                 if (tmp.empty()) {
523                         throw ExceptionMessage(WarningException, _("Missing File"),
524                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
525                         error = true;
526                 } else if (!read(tmp, MERGE)) {
527                         throw ExceptionMessage(WarningException, _("Corrupt File"),
528                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
529                         error = true;
530                 }
531         }
532
533         min_toclevel_ = Layout::NOT_IN_TOC;
534         max_toclevel_ = Layout::NOT_IN_TOC;
535         const_iterator lit = begin();
536         const_iterator len = end();
537         for (; lit != len; ++lit) {
538                 int const toclevel = lit->toclevel;
539                 if (toclevel != Layout::NOT_IN_TOC) {
540                         if (min_toclevel_ == Layout::NOT_IN_TOC)
541                                 min_toclevel_ = toclevel;
542                         else
543                                 min_toclevel_ = min(min_toclevel_, toclevel);
544                         max_toclevel_ = max(max_toclevel_, toclevel);
545                 }
546         }
547         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
548                 << ", maximum is " << max_toclevel_);
549
550         return !error;
551 }
552
553
554 void TextClass::readTitleType(Lexer & lexrc)
555 {
556         keyword_item titleTypeTags[] = {
557                 { "commandafter", TITLE_COMMAND_AFTER },
558                 { "environment", TITLE_ENVIRONMENT }
559         };
560
561         PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
562
563         int le = lexrc.lex();
564         switch (le) {
565         case Lexer::LEX_UNDEF:
566                 lexrc.printError("Unknown output type `$$Token'");
567                 return;
568         case TITLE_COMMAND_AFTER:
569         case TITLE_ENVIRONMENT:
570                 titletype_ = static_cast<TitleLatexType>(le);
571                 break;
572         default:
573                 lyxerr << "Unhandled value " << le
574                        << " in TextClass::readTitleType." << endl;
575
576                 break;
577         }
578 }
579
580
581 void TextClass::readOutputType(Lexer & lexrc)
582 {
583         keyword_item outputTypeTags[] = {
584                 { "docbook", DOCBOOK },
585                 { "latex", LATEX },
586                 { "literate", LITERATE }
587         };
588
589         PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
590
591         int le = lexrc.lex();
592         switch (le) {
593         case Lexer::LEX_UNDEF:
594                 lexrc.printError("Unknown output type `$$Token'");
595                 return;
596         case LATEX:
597         case DOCBOOK:
598         case LITERATE:
599                 outputType_ = static_cast<OutputType>(le);
600                 break;
601         default:
602                 lyxerr << "Unhandled value " << le
603                        << " in TextClass::readOutputType." << endl;
604
605                 break;
606         }
607 }
608
609
610 enum ClassOptionsTags {
611         CO_FONTSIZE = 1,
612         CO_PAGESTYLE,
613         CO_OTHER,
614         CO_HEADER,
615         CO_END
616 };
617
618
619 void TextClass::readClassOptions(Lexer & lexrc)
620 {
621         keyword_item classOptionsTags[] = {
622                 {"end", CO_END },
623                 {"fontsize", CO_FONTSIZE },
624                 {"header", CO_HEADER },
625                 {"other", CO_OTHER },
626                 {"pagestyle", CO_PAGESTYLE }
627         };
628
629         lexrc.pushTable(classOptionsTags, CO_END);
630         bool getout = false;
631         while (!getout && lexrc.isOK()) {
632                 int le = lexrc.lex();
633                 switch (le) {
634                 case Lexer::LEX_UNDEF:
635                         lexrc.printError("Unknown ClassOption tag `$$Token'");
636                         continue;
637                 default: break;
638                 }
639                 switch (static_cast<ClassOptionsTags>(le)) {
640                 case CO_FONTSIZE:
641                         lexrc.next();
642                         opt_fontsize_ = rtrim(lexrc.getString());
643                         break;
644                 case CO_PAGESTYLE:
645                         lexrc.next();
646                         opt_pagestyle_ = rtrim(lexrc.getString());
647                         break;
648                 case CO_OTHER:
649                         lexrc.next();
650                         options_ = lexrc.getString();
651                         break;
652                 case CO_HEADER:
653                         lexrc.next();
654                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
655                         break;
656                 case CO_END:
657                         getout = true;
658                         break;
659                 }
660         }
661         lexrc.popTable();
662 }
663
664
665 enum FloatTags {
666         FT_TYPE = 1,
667         FT_NAME,
668         FT_PLACEMENT,
669         FT_EXT,
670         FT_WITHIN,
671         FT_STYLE,
672         FT_LISTNAME,
673         FT_BUILTIN,
674         FT_END
675 };
676
677
678 void TextClass::readFloat(Lexer & lexrc)
679 {
680         keyword_item floatTags[] = {
681                 { "end", FT_END },
682                 { "extension", FT_EXT },
683                 { "guiname", FT_NAME },
684                 { "latexbuiltin", FT_BUILTIN },
685                 { "listname", FT_LISTNAME },
686                 { "numberwithin", FT_WITHIN },
687                 { "placement", FT_PLACEMENT },
688                 { "style", FT_STYLE },
689                 { "type", FT_TYPE }
690         };
691
692         lexrc.pushTable(floatTags, FT_END);
693
694         string type;
695         string placement;
696         string ext;
697         string within;
698         string style;
699         string name;
700         string listName;
701         bool builtin = false;
702
703         bool getout = false;
704         while (!getout && lexrc.isOK()) {
705                 int le = lexrc.lex();
706                 switch (le) {
707                 case Lexer::LEX_UNDEF:
708                         lexrc.printError("Unknown float tag `$$Token'");
709                         continue;
710                 default: break;
711                 }
712                 switch (static_cast<FloatTags>(le)) {
713                 case FT_TYPE:
714                         lexrc.next();
715                         type = lexrc.getString();
716                         if (floatlist_.typeExist(type)) {
717                                 Floating const & fl = floatlist_.getType(type);
718                                 placement = fl.placement();
719                                 ext = fl.ext();
720                                 within = fl.within();
721                                 style = fl.style();
722                                 name = fl.name();
723                                 listName = fl.listName();
724                                 builtin = fl.builtin();
725                         } 
726                         break;
727                 case FT_NAME:
728                         lexrc.next();
729                         name = lexrc.getString();
730                         break;
731                 case FT_PLACEMENT:
732                         lexrc.next();
733                         placement = lexrc.getString();
734                         break;
735                 case FT_EXT:
736                         lexrc.next();
737                         ext = lexrc.getString();
738                         break;
739                 case FT_WITHIN:
740                         lexrc.next();
741                         within = lexrc.getString();
742                         if (within == "none")
743                                 within.erase();
744                         break;
745                 case FT_STYLE:
746                         lexrc.next();
747                         style = lexrc.getString();
748                         break;
749                 case FT_LISTNAME:
750                         lexrc.next();
751                         listName = lexrc.getString();
752                         break;
753                 case FT_BUILTIN:
754                         lexrc.next();
755                         builtin = lexrc.getBool();
756                         break;
757                 case FT_END:
758                         getout = true;
759                         break;
760                 }
761         }
762
763         // Here if have a full float if getout == true
764         if (getout) {
765                 Floating fl(type, placement, ext, within,
766                             style, name, listName, builtin);
767                 floatlist_.newFloat(fl);
768                 // each float has its own counter
769                 counters_.newCounter(from_ascii(type), from_ascii(within),
770                                       docstring(), docstring());
771                 // also define sub-float counters
772                 docstring const subtype = "sub-" + from_ascii(type);
773                 counters_.newCounter(subtype, from_ascii(type),
774                                       "\\alph{" + subtype + "}", docstring());
775         }
776
777         lexrc.popTable();
778 }
779
780
781 enum CounterTags {
782         CT_NAME = 1,
783         CT_WITHIN,
784         CT_LABELSTRING,
785         CT_LABELSTRING_APPENDIX,
786         CT_END
787 };
788
789
790 void TextClass::readCounter(Lexer & lexrc)
791 {
792         keyword_item counterTags[] = {
793                 { "end", CT_END },
794                 { "labelstring", CT_LABELSTRING },
795                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
796                 { "name", CT_NAME },
797                 { "within", CT_WITHIN }
798         };
799
800         lexrc.pushTable(counterTags, CT_END);
801
802         docstring name;
803         docstring within;
804         docstring labelstring;
805         docstring labelstring_appendix;
806
807         bool getout = false;
808         while (!getout && lexrc.isOK()) {
809                 int le = lexrc.lex();
810                 switch (le) {
811                 case Lexer::LEX_UNDEF:
812                         lexrc.printError("Unknown counter tag `$$Token'");
813                         continue;
814                 default: break;
815                 }
816                 switch (static_cast<CounterTags>(le)) {
817                 case CT_NAME:
818                         lexrc.next();
819                         name = lexrc.getDocString();
820                         if (counters_.hasCounter(name))
821                                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
822                         else
823                                 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
824                         break;
825                 case CT_WITHIN:
826                         lexrc.next();
827                         within = lexrc.getDocString();
828                         if (within == "none")
829                                 within.erase();
830                         break;
831                 case CT_LABELSTRING:
832                         lexrc.next();
833                         labelstring = lexrc.getDocString();
834                         labelstring_appendix = labelstring;
835                         break;
836                 case CT_LABELSTRING_APPENDIX:
837                         lexrc.next();
838                         labelstring_appendix = lexrc.getDocString();
839                         break;
840                 case CT_END:
841                         getout = true;
842                         break;
843                 }
844         }
845
846         // Here if have a full counter if getout == true
847         if (getout)
848                 counters_.newCounter(name, within, 
849                                       labelstring, labelstring_appendix);
850
851         lexrc.popTable();
852 }
853
854
855 bool TextClass::hasLayout(docstring const & n) const
856 {
857         docstring const name = n.empty() ? defaultLayoutName() : n;
858
859         return find_if(layoutlist_.begin(), layoutlist_.end(),
860                        LayoutNamesEqual(name))
861                 != layoutlist_.end();
862 }
863
864
865
866 Layout const & TextClass::operator[](docstring const & name) const
867 {
868         BOOST_ASSERT(!name.empty());
869
870         const_iterator it = 
871                 find_if(begin(), end(), LayoutNamesEqual(name));
872
873         if (it == end()) {
874                 lyxerr << "We failed to find the layout '" << to_utf8(name)
875                        << "' in the layout list. You MUST investigate!"
876                        << endl;
877                 for (const_iterator cit = begin(); cit != end(); ++cit)
878                         lyxerr  << " " << to_utf8(cit->name()) << endl;
879
880                 // we require the name to exist
881                 BOOST_ASSERT(false);
882         }
883
884         return *it;
885 }
886
887
888 Layout & TextClass::operator[](docstring const & name)
889 {
890         BOOST_ASSERT(!name.empty());
891
892         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
893
894         if (it == end()) {
895                 lyxerr << "We failed to find the layout '" << to_utf8(name)
896                        << "' in the layout list. You MUST investigate!"
897                        << endl;
898                 for (const_iterator cit = begin(); cit != end(); ++cit)
899                         lyxerr  << " " << to_utf8(cit->name()) << endl;
900
901                 // we require the name to exist
902                 BOOST_ASSERT(false);
903         }
904
905         return *it;
906 }
907
908
909 bool TextClass::deleteLayout(docstring const & name)
910 {
911         if (name == defaultLayoutName() || name == emptyLayoutName())
912                 return false;
913
914         LayoutList::iterator it =
915                 remove_if(layoutlist_.begin(), layoutlist_.end(),
916                           LayoutNamesEqual(name));
917
918         LayoutList::iterator end = layoutlist_.end();
919         bool const ret = (it != end);
920         layoutlist_.erase(it, end);
921         return ret;
922 }
923
924
925 // Load textclass info if not loaded yet
926 bool TextClass::load(string const & path) const
927 {
928         if (loaded_)
929                 return true;
930
931         // Read style-file, provided path is searched before the system ones
932         FileName layout_file;
933         if (!path.empty())
934                 layout_file = FileName(addName(path, name_ + ".layout"));
935         if (layout_file.empty() || !layout_file.exists())
936                 layout_file = libFileSearch("layouts", name_, "layout");
937         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
938
939         if (!loaded_) {
940                 lyxerr << "Error reading `"
941                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
942                        << "'\n(Check `" << name_
943                        << "')\nCheck your installation and "
944                         "try Options/Reconfigure..." << endl;
945         }
946
947         return loaded_;
948 }
949
950
951 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
952 {
953         docstring n = name;
954         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
955         while (!n.empty()) {
956                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
957                 if (cit != cen && cit->first == n)
958                         return cit->second;
959                 size_t i = n.find(':');
960                 if (i == string::npos)
961                         break;
962                 n = n.substr(0,i);
963         }
964         return empty_insetlayout_;
965 }
966
967
968 docstring const & TextClass::defaultLayoutName() const
969 {
970         // This really should come from the actual layout... (Lgb)
971         return defaultlayout_;
972 }
973
974
975 Layout const & TextClass::defaultLayout() const
976 {
977         return operator[](defaultLayoutName());
978 }
979
980
981 bool TextClass::isDefaultLayout(Layout const & lay) const 
982 {
983         return lay.name() == defaultLayoutName();
984 }
985
986
987 bool TextClass::isEmptyLayout(Layout const & lay) const 
988 {
989         return lay.name() == emptyLayoutName();
990 }
991
992
993 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
994 {
995         DocumentClass * dc = new DocumentClass(baseClass);
996         tc_list_.push_back(dc);
997         return *tc_list_.back();
998 }
999
1000
1001 DocumentClassBundle & DocumentClassBundle::get()
1002 {
1003         static DocumentClassBundle singleton; 
1004         return singleton; 
1005 }
1006
1007
1008 DocumentClass::DocumentClass(LayoutFile const & tc)
1009         : TextClass(tc)
1010 {}
1011
1012
1013 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1014 {
1015         LayoutList::const_iterator it  = layoutlist_.begin();
1016         LayoutList::const_iterator end = layoutlist_.end();
1017         for (; it != end; ++it)
1018                 if (it->latexname() == lay)
1019                         return true;
1020         return false;
1021 }
1022
1023
1024 bool DocumentClass::provides(string const & p) const
1025 {
1026         return provides_.find(p) != provides_.end();
1027 }
1028
1029
1030 bool DocumentClass::hasTocLevels() const
1031 {
1032         return min_toclevel_ != Layout::NOT_IN_TOC;
1033 }
1034
1035
1036 ostream & operator<<(ostream & os, PageSides p)
1037 {
1038         switch (p) {
1039         case OneSide:
1040                 os << '1';
1041                 break;
1042         case TwoSides:
1043                 os << '2';
1044                 break;
1045         }
1046         return os;
1047 }
1048
1049
1050 } // namespace lyx